简体   繁体   English

Java遍历一维数组和二维数组

[英]Java iterate through 1D array and 2D array

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.我想打印“最喜欢的糖果”,然后打印 1-8 个糖果,然后打印“霍格沃茨最喜欢的科目”,然后打印 1-10 个科目,然后是“梦想假期”,然后打印 1-7 个假期。

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 1.酸爆米花

2.Sherbert Lemons 2.舍伯特柠檬

3.Bertie Bott's Every Flavour Beans 3.Bertie Bott's Every Flavor Beans

4.Cake 4.蛋糕

5.Hagrid's Rock Cakes 5.海格的岩石蛋糕

6.Chocolate Frogs 6.巧克力蛙

7.Ginger Newt 7.姜蝾螈

8.I hate sweets 8.我讨厌甜食

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8

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这背后的想法是为每个问题打印出选择数组中与问题数组具有相同索引的所有答案,直到该数组的末尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM