英文:
Error in printing elements of an Multidimensional Array (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("在第" + i + "行,第" + j + "列的元素为" + matrix[i][j]);
}
}
英文:
I want to print all the elements of the matrix. But the complier throws "Cannot find symbol" error. I want to know the exact problem and its remedy.
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
得分: 2
你有两个问题:
-
你需要迭代索引,而不是对象。
-
在应该有一个开括号(“{”)的地方,你有一个“;”。
for (int i = 0; i < matrix.length; i += 1) {
for (int j = 0; j < matrix[i].length; j += 1) {
System.out.println("在第 " + i + " 行,第 " + j + " 列 = " + matrix[i][j]);
}
}
在第 0 行,第 0 列 = 3
在第 0 行,第 1 列 = 2
在第 0 行,第 2 列 = 1
在第 1 行,第 0 列 = 3
在第 1 行,第 1 列 = 2
在第 1 行,第 2 列 = 1
在第 2 行,第 0 列 = 5
在第 2 行,第 1 列 = 5
在第 2 行,第 2 列 = 8
英文:
You have two issues:
-
You need to iterate over the indexes and not the objects
-
You have a ";" where you should have an opening brace ("{")
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
得分: 2
Allen已经指出了你的错误。
如果你想用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("行 --> ");
for (int j : i) {
System.out.print(j + " ");
}
System.out.println();
}
}
英文:
Allen already point out your mistakes.
If you want to achieve the same with foreach loop :
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论