在我的代码中使用扫描仪时如何修复找不到行错误?

问题描述 投票:0回答:3

我运行代码时不断收到此异常:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Unknown Source)
at BattleshipCheck.generateGrid(BattleshipCheck.java:60)

这是我的代码:

public static int[][] generateGrid(Scanner in, int gridSize) {
    int[][] grid = new int[gridSize][gridSize];
    while(in.hasNextLine()) {
    in.nextLine();
    in.nextLine();
    String[] currentLine = in.nextLine().split("\\s+");
    for (int row = 0; row < gridSize; row++) {
        for (int column = 0; column < gridSize; column++) {
             grid[row][column] = Integer.parseInt(currentLine[column]);
        }
    }
    }
    return grid;


}

我正试着从第三行开始阅读,所以我使用.nextLine两次,我在想我的问题所在,但我不知道如何修复它

java arrays java.util.scanner
3个回答
0
投票

如果要从第三行开始,请在while-Loop之前调用nextLine(),而不是在其中。一旦你在最后一行,你尝试跳过另外两行,这些行不存在。在跳过两行之前,您还必须检查文件是否实际上有三行。

public static int[][] generateGrid(Scanner in, int gridSize) {
int[][] grid = new int[gridSize][gridSize];

if(in.hasNextLine())in.nextLine();
if(in.hasNextLine())in.nextLine();

while(in.hasNextLine()) {
String[] currentLine = in.nextLine().split("\\s+");
for (int row = 0; row < gridSize; row++) {
    for (int column = 0; column < gridSize; column++) {
         grid[row][column] = Integer.parseInt(currentLine[column]);
    }
}
}
return grid;

}


1
投票

看起来你忽略了文件中的数据。它告诉你有多少行。此外,不需要while循环。

public static int[][] generateGrid(Scanner in) {
    // Get gridSize from file
    int gridSize = Integer.parseInt(in.nextLine());
    int[][] grid = new int[gridSize][gridSize];

    // Not sure what 2nd line is for
    // I'm guessing it is the number of ships followed
    // by the size of each ship
    in.nextLine();

    for (int row = 0; row < gridSize; row++) {
        // Move this here
        String[] currentLine = in.nextLine().split("\\s+");
        for (int column = 0; column < gridSize; column++) {
             grid[row][column] = Integer.parseInt(currentLine[column]);
        }
    }

    return grid;
}

如果文件格式错误,您仍需要添加错误检查。虽然我会原样离开,但如果出现问题,它会抛出异常。让调用函数处理它。


-1
投票
int i=0;
public static int[][] generateGrid(Scanner in, int gridSize) {
    int[][] grid = new int[gridSize][gridSize];
    while(in.hasNextLine()) {
        if(++i < 2) {
            in.nextLine();
            continue;
        }
        String[] currentLine = in.nextLine().split("\\s+");
        for (int row = 0; row < gridSize; row++) {
            for (int column = 0; column < gridSize; column++) {
                 grid[row][column] = Integer.parseInt(currentLine[column]);
            }
        }
    }
    return grid;


}
© www.soinside.com 2019 - 2024. All rights reserved.