我有一系列问题和一系列答案。我正在尝试打印一个问题和该问题的多项选择答案并获得用户输入然后返回并获得第二个问题并打印出来自2D阵列的多项选择答案。抱歉,如果混淆。 代码:
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"}
};
我想打印出“最喜欢的甜点”然后1-8个糖果然后打印“霍格沃茨最喜欢的主题”然后1-10个主题然后“梦想假期”并打印1-7个假期。
我的代码是垃圾,但在这里是:
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]);
}
}
}
这就是我运行时我的代码所发生的事情:
最喜欢的甜蜜
1.Acid Pops
2.Sherbert Lemons3.Bertie Bott's Every Flavor Beans
4.Cake
5.Hagrid的Rock Cakes
6.Chocolate Frogs
7.Ginger Newt
8.我讨厌甜食
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:8
答案 0 :(得分:2)
既然你说你的代码不好我就有权完全重写它,它对我有用:
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]);
}
}
这背后的想法是每个问题打印出选择数组中与问题数组具有相同索引直到该数组末尾的所有答案