[英]Java Looping through 2D array - Homework
我必须遍历2D数组,创建并存储一个随机问题,并测试用户的响应。 但是,我不知道如何正确引用这些元素。 我习惯使用(counter; counter <x; 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
}
您的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]
。
看来您无法像我打算的那样使用for-each循环来更改数组的元素。 我将不得不使用计数器的典型for循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.