java - 使用 Scanner 初始化二维数组。尝试显示二维数组时,数组值全部为空
问题描述
我一直对学习面向对象的编程语言很感兴趣,并且刚刚接触到 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
推荐阅读
- java - 缓冲阅读器抛出异常
- testing - 赛普拉斯,如何检查属性是否存在
- python - Fizzbuzz Challenge in Twilio quest
- html - 如何在 WordPress 中让这些行彼此相邻?
- python - tkinter - 为什么会有像 bbox 这样的东西?
- python - Tensorflow:PartialTensorShape:合并期间不兼容的等级:2 vs. 1
- php - 调用未定义的函数 apcu_add()
- c# - 内联方法以提高性能,但在 C# 中执行速度较慢
- c# - 在数据网格中添加下拉列
- c# - 为 Safari 下载的文件名无法打印瑞典语字符