繁体   English   中英

如何接受来自用户的值并将其存储到 Java 中的二维数组中?

[英]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]);
        }
    }

行和列的值为 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]);
    } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM