Katherine99
Katherine99

Reputation: 990

Android/Java : Returning postion of Array

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().

Upvotes: 0

Views: 69

Answers (3)

g00dy
g00dy

Reputation: 6778

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.

Upvotes: 0

test
test

Reputation: 2618

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];
}

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 1

Related Questions