首页 > 解决方案 > Java循环遍历二维数组 - 作业

问题描述

我必须遍历一个二维数组,创建并存储一个随机问题,并测试用户的响应。但是,我不知道如何正确引用这些元素。我习惯了 (counter; counter < x; counter++) 的旧语法。

如何使用此语法引用特定的数组元素?这让我很困惑。我需要引用行中的第 5 个元素以查看用户输入的内容以从循环中中断,并且还需要循环并将一维数组转置到二维数组的当前行中。

    for(int arrRow[] : arr)                 //arr is a [100][5] array
    {
        switch(rNum.nextInt(4))             //Creates a random number between 0 and 3 and passes it to a switch statement
        {
            case 0:                         //Generates an Addition question
                arr2 = a.quiz();
                break;
            case 1:                         //Generates a Subtraction question
                arr2 = s.quiz();
                break;
            case 2:                         //Generates a Multiplication question
                arr2 = m.quiz();
                break;
            case 3:                         //Generates a Division question
                arr2 = d.quiz();
        }

        //for (colNum=0; colNum<5;colNum++) //loops through the column in the 2D array and pulls data from returned array
        for(int arrCol : arrRow)
        {
            arrCol = arr2[arrCol];
        }

        if(arrRow[4] == -1)                 //If user enters a -1, breaks from the for loop
        {
            break;
        }
    }
    newTest.printQuestionResult();          //Calls the print function after the user is done or the test is complete
}

标签: javaarrays2d

解决方案


arrColint一个原始类型变量,所以这个变量是一个从arrRow. 如果您为 分配任何值arrCol,它将不会反映在 中arrRow

你应该这样做:

for (int index = 0; index < arrRow.length; i++)
{
    int col = arrRow[index];
    arrRow[index] = arr2[col];
}

我不确定arr2包含什么,所以我不确定你ArrayIndexOutOfBoundsException在阅读它的元素时是否会遇到这样的情况。

我猜你需要arr2[index]而不是arr2[col].


推荐阅读