Olivr3000 Olivr3000 - 5 months ago 10
Android Question

Contents of str as a name of array

My problem seems simple, so hopefully I can find the answer quickly.

To summarize my code, I generate a random number between 1 & 2. With that I have a string

questionName
containing
easy1
or
easy2
(
"easy" + randomNum
) depending on the random number. I want to print the contents of
questionName
but instead of a string, get the array
easy1[0]
or
easy2[0]
.

public void generateQuestion() {
int min = 1;
int max = 2;


Random r = new Random();
int questionToBeSelected = r.nextInt(max - min + 1) + min;

System.out.println(questionToBeSelected);

String questionName = "easy" + questionToBeSelected;

String[] easy1 = {
"In The Phantom Menace, who are the first two characters on screen?", //Question, obviously
"3", //The array child that is correct
"Padme and Annie", //Answer 1
"Obi-Wan and Qui-Gon Jinn", //Answer 2
"Jar Jar Binks", //Answer 3
"Annie and Obi-Wan" //Answer 4
};

String[] easy2 = {
"Sample question",
"2",
"Sample answer",
"Sample answer",
"Sample answer",
"Sample answer",
};

System.out.println(easy1[0]);

TextView questionPlaceholder = (TextView) findViewById(R.id.game_question);
questionPlaceholder.setText(questionName[0]); // <-------- Problem :(

String alreadyPlayedQuestions;
String questionNumber;
}


Thanks

Answer

Could you please have a look at the following:

public void generateQuestion() {
    int min = 0;
    int max = 1;
    Random r = new Random();
    int questionToBeSelected = r.nextInt(max - min + 1) + min;
    System.out.println(questionToBeSelected);
    String[] easy1 = {
            "In The Phantom Menace, who are the first two characters on screen?", //Question, obviously
            "3", //The array child that is correct
            "Padme and Annie", //Answer 1
            "Obi-Wan and Qui-Gon Jinn", //Answer 2
            "Jar Jar Binks", //Answer 3
            "Annie and Obi-Wan" //Answer 4
    };
    String[] easy2 = {
            "Sample question",
            "2", // array index that is correct
            "Sample answer",
            "Wrong answer1",
            "Wrong answer2",
            "Wrong answer3",
    };
    String[] questionName = new String[][]{easy1, easy2}[questionToBeSelected];
    System.out.println(easy1[0]);
    TextView questionPlaceholder = (TextView) findViewById(R.id.game_question);
    System.out.println(questionName[0]);
    questionPlaceholder.setText(questionName[0]);  //   <-------- Problem :(
    String alreadyPlayedQuestions;
    String questionNumber;
}

Very little changes have been made to your method. Please tell me this is what you wanted to achieve or not.