我必须遍历2D数组,创建并存储随机问题,并测试用户的响应。但是,我不知道如何正确引用这些元素。我习惯使用(counter; counter 如何使用这种语法引用特定的数组元素?这让我很困惑。我需要引用该行中的第5个元素,以查看用户输入的内容以从循环中打破,并循环遍历并将1D数组转置为2D数组的当前行。 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
}
答案 0 :(得分:2)
您的arrCol
是一个int
,它是原始类型变量,因此此变量是从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]
。
答案 1 :(得分:0)
似乎您不能像我打算的那样使用for-each循环来更改数组的元素。我将不得不使用计数器的典型for循环。