简体   繁体   中英

Why do I get a java.util.NoSuchElementException, when I'm trying to use the scanner

So I'm trying to read a file with names in them and I want to make a list with all the people in the file. The text file is called people.txt and is structured as: surname/lastname\\nsurname/lastname and so on. The file should be located in the right place.

Code:

public class UI {
public static void main(String[] args) {
    String naam;
    ArrayList <Person> people = new ArrayList<>();
    Scanner sc = new Scanner("people.txt");
    while(sc.hasNextLine()) {
        Scanner line = new Scanner(sc.nextLine());
        line.useDelimiter("/");
        String name = line.next();
        String surname= line.next();
        Person a = new Person(name, surname);
        people.add(a);
    }
    System.out.println(people.size());
}

Error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at domain.UI.main(UI.java:14)

The problem is here:

Scanner sc = new Scanner("people.txt");

This doesn't make a new Scanner getting information from a file called people.txt. It makes a new Scanner which literally contains the text "people.txt". Since there's only one line, it throws an error when you try to get the second line.

Sounds like you want to use the following constructor:

Scanner(Path source)

Where you use the Interface Path object in Class Scanner .

Path p1 = Paths.get(“people.tx”);
Scanner sc = new Scanner(p1);

You are not reading the file, instead the text "people.txt" and thus line.useDelimiter("/"); has no effect. You are getting the error because String name = line.next(); consumes the text "people.txt" and there is no text left and String surname= line.next(); throwa the exception

You need to use java.io.File like below:

Scanner sc = new Scanner(new File("pathToFile/people.txt"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM