I have to loop through a 2D array, create and store a random question, and test the user's response. However, I can't figure out how to properly reference the elements. I'm use to the old syntax of (counter; counter < x; counter++).
How do I reference a specific array element with this syntax? It's quite confusing to me. I need to reference the 5th element in the row to see what the user entered to break from the loop and also to loop through and transpose a 1D array into the 2D array's current row.
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 = arr2[arrCol];The codefor(int arrCol : arrRow)already assigns the value toarrColarr2supposed to contain? And what values doarrColhold that made it the index ofarr2? What is clear isarrCol = arr2[arrCol];is definitely wrong as you are assigning a primitive variable (referenced by value) with new value, which wouldn't change anything.for (int y = 0; y < arr.length; y++) { for (int x = 0; x < arr[y].length; x++) { System.out.print(arr[y][x] + "\t"); } System.out.println(""); }.