java - 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
}
解决方案
你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]
.
推荐阅读
- kubernetes - localstack k8s 部署 yaml 和健康检查端点
- automata - L = {w ∈ {a, b}*, Na(w) mod 2 = 1} 的正则表达式
- python - 使用 statsmodels.tsa.arima 对 ARIMAX 系数进行零限制
- file-io - 如何有效地监视大量文件更改?
- datajoint - 从表中备份/删除的最快方法
- php - 停止 Mediawiki tinymce 编辑器以转换 html 代码
- sql-server - cPanel 错误 - pyodbc 的构建轮失败
- reactjs - 无法将类转换为功能组件,“未安装错误”
- flutter - 如何创建排序列表的新列表
- android - 如何从 Firebase 存储中检索 gif 资产?Kotlin 安卓工作室