在代码中使用扫描仪时,如何解决找不到行的错误?

时间:2018-11-21 16:39:14

标签: java arrays java.util.scanner

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

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两次,我想这就是我的问题所在,但我不确定如何解决

3 个答案:

答案 0 :(得分: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 :(得分:0)

如果要从第三行开始,请在while循环之前而不是在其内部调用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;

}

答案 2 :(得分:-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;


}