Java - 文本到2d数组删除空格“

时间:2017-10-08 11:14:01

标签: java arrays

让文本文件包含一个带有固定行和列的二维数组[6] [3]

a 5 7
b 9 7
c 1 0
d 0 5
e 8 7
f 0 4   

我需要将数据放入数组playerOne[][]

这是我的代码

try {
        Scanner sc = new Scanner(new File("test.txt"));
        while (sc.hasNextLine()) {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 3; j++) {
                    String line = sc.next().trim();
                    if (line.length() > 0) {
                        playerOne[i][j] = line;
                        System.out.println(i+ " " +j+ " "+ line);
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.print(Arrays.toString(playerOne));
}

我收到NoSuchElementException错误,它无法打印数组

1 个答案:

答案 0 :(得分:1)

而不是直接使用nextLine使用.next .next将获得下一个值,而不管下一个值行

try {
        Scanner sc = new Scanner(new File("test.txt"));
        while (sc.hasNext()) {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 3; j++) {
                    String nextValue= sc.next().trim();
                        playerOne[i][j] = nextValue;
                        System.out.println(i+ " " +j+ " "+ nextValue);

                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.print(Arrays.toString(playerOne));
}