有 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]);
}
}

共 (2) 个答案

  1. # 1 楼答案

    艾伦已经指出了你的错误。 如果希望通过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();
            }
        }
    
  2. # 2 楼答案

    你有两个问题:

    1. 你需要迭代索引,而不是对象

    2. 你有一个“;”你应该有一个大括号(“{”)

            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