[英]Initialized a Two Dimensional Array using Scanner. When trying to display two dimensional array, array values are all nulled
我一直对学习面向对象的编程语言很感兴趣,并且刚接触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)
我做错了什么? 我在这里先向您的帮助表示感谢。
您需要颠倒将输入值分配给数组元素的方式。 需要将值分配给该变量的变量应位于左侧。 valElement = scan.nextInt();
之后的行 需要从-更改
valElement = x[row][col];
至
x[row][col] = valElement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.