英文:
How to accept values from user and store it into 2D array in Java?
问题
我已经创建了一个二维数组来接收用户输入的值。然而,当我运行代码并尝试输入值时,它不接受这些值。
int rows = 0;
int cols = 0;
int[][] Array = new int[rows][cols];
Scanner entry = new Scanner(System.in);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
Array[rows][cols] = entry.nextInt();
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.println(Array[rows][cols]);
}
}
英文:
I have created a 2D array to accept values from users. However, when I ran the code and tried to input values, it's not accepting the values.
int rows = 0;
int cols = 0;
int[][] Array = new int[rows][cols];
Scanner entry = new Scanner(System.in);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
Array[rows][cols] = entry.nextInt();
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.println(Array[rows][cols]);
}
}
答案1
得分: 0
代码中的行数和列数的值都是0,而你正在创建一个具有行数和列数大小的数组。因此,你的数组大小将为0,不会接受任何值。尝试更改行数和列数的值。
int rows = 5;
int cols = 5;
int[][] Array = new int[rows][cols]; // new int[5][5];
Scanner entry = new Scanner(System.in);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
Array[i][j] = entry.nextInt();
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.println(Array[i][j]);
}
}
英文:
The value of rows and columns is 0 and you are creating an array with rows and columns size. So your array will be of size 0 and won't accept any values. Try to change the values of rows and columns.
int rows = 5;
int cols = 5;
int[][] Array = new int[rows][cols]; // new int[5][5];
Scanner entry = new Scanner(System.in);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
Array[i][j] = entry.nextInt();
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.println(Array[i][j]);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论