读入值以插入2d数组

时间:2017-01-25 22:22:12

标签: java arrays for-loop input

我正在进行一项任务,我需要从文件中读取示例输入并将其插入到2D数组中。以下是输入示例:

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 
    }

赋值声明我不能使用递归,我必须使用2D数组。我已经看过其他问题,但仍然无法弄明白。 谢谢你的帮助!!

1 个答案:

答案 0 :(得分:2)

你读了整行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);

这样你应该阅读所有不是&#34; &#34;