我运行代码时不断收到此异常:
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两次,我在想我的问题所在,但我不知道如何修复它
如果要从第三行开始,请在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;
}
看起来你忽略了文件中的数据。它告诉你有多少行。此外,不需要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;
}
如果文件格式错误,您仍需要添加错误检查。虽然我会原样离开,但如果出现问题,它会抛出异常。让调用函数处理它。
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;
}