文本文件的最后一行未正确存储到二维数组中

Last line of textfile not storing correctly into 2D array

我的扫描仪没有正确访问我的文本文件的最后一行,因此将文本文件的最后一行作为全 0 存储到我的二维数组中,而不是实际存在的内容。我相信我已经提供了一切可以提供有关问题所在的上下文的信息,但是如果需要更多信息,我可以更新此问题,在此先感谢。

//Creates 2-d array object, stores values from file.
public DominoSort (String fileName) throws java.io.FileNotFoundException{
    this.grid = new int [7][8]; //2-d array to hold values from text file

    Scanner br = new Scanner(new File(fileName));
    String line = br.nextLine();

    int r = 0;
    int c = 0;

    while (br.hasNextLine) {
        String[] row = line.split("\s+");
        for (String s : row) {
            this.grid[r][c] = Integer.parseInt(s);
            c++;
        }
        line = br.nextLine();
        r++;
        c = 0;
    }

    //this.setS = new ArrayList<>();
    //this.pairMappings = new ArrayList<ArrayList<dominoLocation>>();

    br.close();
}

//Print grid function, prints out the grid
public void printGrid() {
    for(int r = 0; r < this.grid.length; r++) {
        System.out.println("");
        for(int c = 0; c < this.grid[r].length; c++) {
            System.out.print(this.grid[r][c] + " ");
        }
    }
    System.out.println("");
}

//Driver for checking
public static void main(String[] args) throws IOException {
    // String line;
    //System.out.println(new File(".").getAbsolutePath());
    Scanner input = new Scanner(System.in); //get textfile name from user input
    System.out.print("Enter the file name: ");
    String fileName = input.next();

    DominoSort dom = new DominoSort(fileName); //this call populates the 2-d array object
    //dom.solvePuzzle(6);
    dom.printGrid(); //prints 2d array for output

    //dom.solvePuzzle(6);
}

用于测试/预期输出的文本文件:

3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
2 0 3 2 5 0 5 4    {Notice this line}

实际输出:

3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
0 0 0 0 0 0 0 0    {this line is not right}

您的问题出在嵌套的 while/for 循环中。它在读取所有行之前达到结束条件。 (在您阅读最后一行之前,nextLine() 方法没有更多的行)。您可以通过在文件的最后添加额外的 1 或 2 行来看到这一点,使其显示最后几行。 有几种方法可以修复它,其中之一是在 while 循环之后添加一个额外的 for 循环来单独计算最后一行:

    while (br.hasNextLine()) {

        String[] row = line.split("\s+");

        for (String s : row) {
            this.grid[r][c] = Integer.parseInt(s);
            c++;
        }

        line = br.nextLine();
        r++;
        c = 0;
    }

    String[] row = line.split("\s+");
    for (String s : row) {
        this.grid[r][c] = Integer.parseInt(s);
        c++;
    }

或者,不要在第一个 运行:

上增加行
        while (br.hasNextLine()) {

            String[] row = line.split("\s+");

            for (String s : row) {
                this.grid[r][c] = Integer.parseInt(s);
                c++;
            }

            if (r != 0) 
                line = br.nextLine();

            r++;
            c = 0;
        }