0

I'm working on an app that register the answers each user introduces. For this purpose I have an Array where depending on what each user answers.

What I want to do is to get those answers and use them in another class for example in order to serialize these answers in XML.

I would like to know if there is a way of returning in a simpler way the answers. What I have now is the following code but its quite unproductive:

        public static String[] Respuestas = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};

       public static String getRespuesta1(){
            return Respuestas[0];
        }
        public static String getRespuesta2(){
            return Respuestas[1];
        }

And so on until get Respuesta30().

3 Answers 3

3

You do not have to create 30 methods for this situation, can't you simply call:

MyClass.Respuestas[x]; //where x is any number from 0 to 30?

If you really need a method, which, judging by this snippet of code you don't seem to need it, then pass the index as a parameter:

public static String getRespuestaByIndex(int index)
{
    return Respuestas[index];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Add an integer argument to the method getRespuesta that specifies the index you are interested in. Having a separate method for each element is not a good idea at all.

Comments

0

The above method is an obviously better solution for your task, than having 30 functions that do the same thing. One more thing, define the array like this please:

public static String[] Respuestas = new String[30];

You may set the iterations inside the square brackets too [] , but I don't think that you need that.

2 Comments

Hi if i do that it says NullPointerException.
Sorry, corrected it. I don't know why I wrote it, but yeah, the null pointer exception comes from the fact, that there isn't any alocated space for the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.