java - 读取值以插入二维数组

标签 java arrays for-loop input

我正在做一项作业,需要从文件中读取示例输入并将其插入到二维数组中。以下是输入示例:

5 6
1 3 4 B 4 3
0 3 5 0 0 9
0 5 3 5 0 2
4 3 4 0 0 4
0 2 9 S 2 1

5 和 6 是数组的维度。用户必须能够一次输入多个像这样的数组,当用户输入-1时程序结束。这是我到目前为止的代码,似乎没有按预期工作(我打印出数组以确保代码工作):

public static void main (String[] args){
    Scanner sc = new Scanner(System.in);
    int arHeight = sc.nextInt();
    int arWidth = sc.nextInt();
    sc.useDelimiter(" ");
    String[][] map = new String[arHeight][arWidth];

        for(int i=0; i<arHeight; i++){
            for(int j=0; j<arWidth; j++){
                map[i][j] = sc.nextLine();
            }//end inner for
        }//end outter for 

            for(int i=0; i<arHeight; i++){
            for(int j=0; j<arWidth; j++){
                System.out.print(map[i][j] + " ");
            }//end inner for
        }//end outter for 
    }

作业指出我不能使用递归并且必须使用二维数组。我看过其他问题,但似乎仍然无法弄清楚。 感谢您的帮助!!

最佳答案

你读了整行 i*j 次

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            map[i][j] = sc.nextLine();

您还将所有数据保存在字符串数组中,我不知道为什么。解决办法如下:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int arHeight = sc.nextInt();
    int arWidth = sc.nextInt();

    int[][] map = new int[arHeight][arWidth];

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            map[i][j] = sc.nextInt();
        }//end inner for
    }//end outter for

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            System.out.print(map[i][j] + " ");
        }//end inner for
    }

}

然后尝试使用

char[][] map = new char[arHeight][arWidth];

在 for 循环中:

if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0);

这样你应该读取所​​有不是“”的字符。

关于java - 读取值以插入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41862750/

相关文章:

java - 如何删除 Java 字符串中的嵌入式大括号?

jar 文件中的 Java 类加载器

java - 使用 Action 监听器设置目录

java - 如何在不同的计算机上打开导出的.exe Jar文件或RUN.bat文件?

javascript - 使用 ForEach 和 2 个数组来创建一个新对象

ruby - 确定一个数组是否包含ruby中另一个数组的内容

bash - 将 MAC 地址读取到 shell 变量会导致奇怪的行为

arrays - 如何生成包含另一个数组元素的多个数组?

java - 创建一个需要从 3 个变量 ( x y z ) 中间向外循环的检查

python-2.7 - 快速构建一个非常大的稀疏矩阵