Reputation: 37
I have a 1d array of questions and a 2d array of answers. I'm trying to print off one question and the multiple choice answers for that question and get user input then go back and get the second question and print off the multiple choice answers from the 2d array. Sorry if confusing. Code:
private String[] questions =
{"Favourite Sweet", "Favourite subject at Hogwarts", "Dream Vacation"};
private String [][] selection =
{{"1.Acid Pops","2.Sherbert Lemons","3.Bertie Bott's Every Flavour Beans",
"4.Cake","5.Hagrid's Rock Cakes","6.Chocolate Frogs","7.Ginger Newt",
"8.I hate sweets\n"},
{"1.Care of Magical Creatures","2.Charms","3.Defense Against the Dark Arts",
"4.Divination","5.Herbology","6.History of Magic","7.Muggle
Studies","8.Potions", "9.Study of Ancient Runes","10.Transfiguration\n"},
{"1.Anywhere with friends","2.Egypt","3.Hogwarts","4.Museum","5.India","6.Forest",
"7.Can't be bothered with a vacation\n"}
};
I want to print off "Favourite Sweet" and then 1-8 sweets then print "Favourite subject at Hogwarts" then 1-10 subjects then "Dream Vacation" and print 1-7 vacations.
Code I have is garbage but here it is:
public void printQuestion(){
for (rowQ = 0; rowQ <= questions.length; rowQ++){
System.out.println(questions[rowQ]);
for(int rowS = rowQ; rowS <= rowS; rowS++){
for(int colS = rowS; colS <= selection[rowS].length; colS++){
System.out.println(selection[rowS][colS]);
}
}
}
This is what happening with my code now when I run it:
Favourite sweet
1.Acid Pops
2.Sherbert Lemons
3.Bertie Bott's Every Flavour Beans
4.Cake
5.Hagrid's Rock Cakes
6.Chocolate Frogs
7.Ginger Newt
8.I hate sweets
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Upvotes: 2
Views: 715
Reputation: 559
Since you said that your code is not good I took the privilege of rewriting it completely and it works for me:
for (int i = 0 ; i < questions.length ; i++){
System.out.println(questions[i]);
for(int j = 0 ; j < selection[i].length ; j++){
System.out.println(selection[i][j]);
}
}
The Idea behind this is for every question print out all the answers in the selection array that has the same index as the question array up to the end of that array
Upvotes: 2