使用Scanner继续获取NoSuchElementException

adv*_*oge 1 java java.util.scanner

我正在尝试读取由空格分隔的字符串值.一旦我尝试将它们设置为变量,我就会得到NoSuchElementException错误.我之前做过类似的事情而不是整数,而且从来没有得到过这个错误.做一些研究:java.util.NoSuchElementException:从文件中读取单词:它表示hasNext被实现为使用next()而hasNextLine被实现为使用nextLine(),所以我尝试用hasNext()替换hasNextLine() ,但仍然没有.有人可以帮忙吗?

File fileName = new File("maze.txt");
Scanner file = new Scanner(fileName);

while(file.hasNextLine()){
    String line = file.nextLine();
    Scanner scanner = new Scanner(line);

    //error starts from here
    String room = scanner.next();
    String roomName = scanner.next();
    String wall1 = scanner.next();
    String wall2 = scanner.next();
    String wall3 = scanner.next();
    String wall4 = scanner.next();
    scanner.close();
}
file.close();
Run Code Online (Sandbox Code Playgroud)

maze.txt

room 101 wall door0 wall wall
room 404 door0 wall door1 wall
room 420 wall wall wall door1
door door0 0 1 close
door door1 1 2 open
Run Code Online (Sandbox Code Playgroud)

错误:

Exception in thread "main" java.util.NoSuchElementException
 at java.util.Scanner.throwFor(Unknown Source)
 at java.util.Scanner.next(Unknown Source)
 at maze.SimpleMazeGame.main(SimpleMazeGame.java:96)
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 6

你应该检查 next()hasNext().另外,我更喜欢mazes.txt从主文件夹和try-with-resourcesStatement中读取而不是裸,close()并测试空行输入.你可以用类似的东西做到这一点,

File fileName = new File(System.getProperty("user.home"), "maze.txt");
try (Scanner file = new Scanner(fileName)) {
  while (file.hasNextLine()) {
    String line = file.nextLine();
    if (line.isEmpty()) {
      continue;
    }
    Scanner scanner = new Scanner(line);
    // error starts from here
    String room = scanner.hasNext() ? scanner.next() : "";
    String roomName = scanner.hasNext() ? scanner.next() : "";
    String wall1 = scanner.hasNext() ? scanner.next() : "";
    String wall2 = scanner.hasNext() ? scanner.next() : "";
    String wall3 = scanner.hasNext() ? scanner.next() : "";
    String wall4 = scanner.hasNext() ? scanner.next() : "";
  }
} catch (Exception e) {
  e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)