续使用Scanner获取NoSuchElementExcepti

续使用Scanner获取NoSuchElementExcepti

本文介绍了继续使用Scanner获取NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read in string values separated by whitespaces. Once I try to set them to a variable I get a NoSuchElementException Error. I've done similar things before where I had to it with integers instead and never got this error. Doing some research: java.util.NoSuchElementException: Read words from a file: It says that hasNext is implemented to work with next() while hasNextLine is implemented to work with nextLine(), so I tried replacing hasNextLine() with hasNext(), but still nothing. Can anyone help?

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();

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

错误:

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)

推荐答案

您应该使用hasNext()检查每个 next().另外,我更喜欢从主文件夹和mazes.txt > try-with-resources语句而不是裸露的close()并测试输入的空行.你可以用类似的方式做到这一点,

You should be checking each next() with hasNext(). Also, I'd prefer to read the mazes.txt from the home folder and the try-with-resources Statement instead of a bare close() and to test for empty lines of input. You could do that with something like,

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();
}

这篇关于继续使用Scanner获取NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:35