#java #multidimensional-array #compiler-errors
#java — язык #многомерный массив #ошибки компилятора #java
Вопрос:
Я хочу напечатать все элементы матрицы. Но компилятор выдает ошибку «Не удается найти символ». Я хочу знать точную проблему и способы ее решения.
class Main{
public static void main(String[] args){
int[][] matrix = {
{3, 2, 1},
{3, 2, 1},
{5, 5, 8}
};
for (int[] i : matrix);
for ( int j : i);
System.out.println("At Row " i " at column" j " = " matrix[i][j]);
}
}
Ответ №1:
У вас две проблемы:
-
Вам нужно выполнить итерацию по индексам, а не по объектам
-
У вас есть «;», где у вас должна быть открывающая фигурная скобка («{«)
for (int i = 0; i < matrix.length; i = 1) {
for (int j = 0; j < matrix[i].length; j = 1) {
System.out.println("At Row " i " at column" j " = " matrix[i][j]);
}
}
At Row 0 at column0 = 3
At Row 0 at column1 = 2
At Row 0 at column2 = 1
At Row 1 at column0 = 3
At Row 1 at column1 = 2
At Row 1 at column2 = 1
At Row 2 at column0 = 5
At Row 2 at column1 = 5
At Row 2 at column2 = 8
Ответ №2:
Аллен уже указал на ваши ошибки. Если вы хотите добиться того же с помощью цикла foreach :
public static void main(String[] args) {
int[][] matrix = { { 3, 2, 1 }, { 3, 2, 1 }, { 5, 5, 8 } };
for (int[] i : matrix) {
System.out.print("Row --> ");
for (int j : i) {
System.out.print(j " ");
}
System.out.println();
}
}