[英]Java iterate through 1D array and 2D array
我有一組一維問題和一組二維答案。 我正在嘗試打印一個問題和該問題的多項選擇答案並獲取用戶輸入然后返回並獲取第二個問題並從二維數組中打印出多項選擇答案。 抱歉,如果混淆。 代碼:
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.酸爆米花
2.舍伯特檸檬
3.Bertie Bott's Every Flavor Beans
4.蛋糕
5.海格的岩石蛋糕
6.巧克力蛙
7.姜蠑螈
8.我討厭甜食
線程“main”中的異常 java.lang.ArrayIndexOutOfBoundsException: 8
既然你說你的代碼不好,我有幸完全重寫了它,它對我有用:
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]);
}
}
這背后的想法是為每個問題打印出選擇數組中與問題數組具有相同索引的所有答案,直到該數組的末尾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.