使用扫描仪初始化二维数组。尝试显示二维数组时,数组值全部为空

时间:2018-10-20 19:45:06

标签: java arrays

我一直对学习面向对象的编程语言感兴趣,并且刚接触Java。现在,我被困在二维数组上。我写了一个程序,用户在其中设置数组的所有元素的值。我没有遇到任何错误,但是当我显示它时,所有值都为空。

这是代码:

    public class TwoDimensionalArrays {
    public static void main(String[] args) {

        displayTwoDimensionalArray(firstTwoDimensionalArray);

        int secondTwoDimensionalArray[][] = new int[4][3];

        initTwoDimensionalArray(secondTwoDimensionalArray);
        displayTwoDimensionalArray(secondTwoDimensionalArray);



    }
    public static void displayTwoDimensionalArray(int x[][]) {
        for(int row = 0; row < x.length; row++) {
            for(int col = 0; col < x[row].length; col++) {
                System.out.print(x[row][col] + "\t");
            }
            System.out.println();
        }
        System.out.println();
    }
    public static void initTwoDimensionalArray(int x[][]) {

        Scanner scan = new Scanner(System.in);
        int valElement;
        int row;
        int col;

        for(row = 0; row < x.length; row++) {
            for(col = 0; col < x[row].length; col++) {
                System.out.print("Enter the value of row " + row + " and column " + col + ".\t");
                valElement = scan.nextInt();

                valElement = x[row][col];
            }
            System.out.println();
        }

        System.out.println("Two Dimensional Array Initialized");
        System.out.println();
    }         
}

这是控制台的输出:

 run:

Enter the value of row 0 and column 0.  7
Enter the value of row 0 and column 1.  5
Enter the value of row 0 and column 2.  4

Enter the value of row 1 and column 0.  6
Enter the value of row 1 and column 1.  9
Enter the value of row 1 and column 2.  7

Enter the value of row 2 and column 0.  4
Enter the value of row 2 and column 1.  4
Enter the value of row 2 and column 2.  3

Enter the value of row 3 and column 0.  5
Enter the value of row 3 and column 1.  5
Enter the value of row 3 and column 2.  6

Two Dimensional Array Initialized

0   0   0   
0   0   0   
0   0   0   
0   0   0   

BUILD SUCCESSFUL (total time: 16 seconds)

我做错了什么? 感谢您的提前帮助。

1 个答案:

答案 0 :(得分:0)

将输入的值分配给数组元素的方式需要颠倒。需要将值分配给该变量的变量应位于左侧。 valElement = scan.nextInt();之后的行需要从-

更改
valElement = x[row][col];

x[row][col] = valElement