如何从用户那里接收值并将其存储到 Java 的二维数组中?

huangapple go评论83阅读模式
英文:

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 &lt; rows; i++){
        for(int j = 0; j &lt; cols; j++){
            Array[rows][cols] = entry.nextInt();
        }
    }
    
    for(int i = 0; i &lt; rows; i++){
        for(int j = 0; j &lt; 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 &lt; rows; i++){
    for(int j = 0; j &lt; cols; j++){
        Array[i][j] = entry.nextInt();
    }
}
for(int i = 0; i &lt; rows; i++){
    for(int j = 0; j &lt; cols; j++){
        System.out.println(Array[i][j]);
    } 
}

huangapple
  • 本文由 发表于 2020年9月4日 01:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63728848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定