1

I'm trying to read data from a file containing multiple lines of "name, int month, int date, int year" information. The Person object takes those items as its constructor parameters. When I try to read from the file, though, and populate a list, I get the following error:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at lab03.PersonSort.populate(PersonSort.java:56)
    at lab03.PersonSort.main(PersonSort.java:38)

Here's my code:

   public static void main(String[] args) throws Exception {

    ArrayList<Person> people = new ArrayList<Person>();

    populate(people);
    //selectionSort(people);

    int index = 0;
    while (index < people.size())
    {
        System.out.println(people.get(index));
        index++;
    }

}

public static ArrayList populate(ArrayList<Person> array) {
    final String PERSON_FILE = ".\\src\\Persons.txt";
    Scanner input = new Scanner(PERSON_FILE);

    while (input.hasNext()) {
        String name = input.next();
        int month = input.nextInt();
        int day = input.nextInt();
        int year = input.nextInt();
        Person temp = new Person(name, month, day, year);
        array.add(temp);
    }

    return array;
}

The persons.txt file has this content:

Merli 9 10 1998

Elijah 3 19 2013

Christine 7 29 1981

Annie 8 28 2002

Bella 8 28 2010

Matt 9 11 1952

Cassidy 8 5 1997

1
  • 1
    Show us a sample Persons.txt.
    – sandris
    Sep 6, 2015 at 19:39

1 Answer 1

0

The reason is that you're trying to parse the string ".\\src\\Persons.txt" rather than the contents of the file. Writing Scanner input = new Scanner(new File(PERSON_FILE).toPath()); should fix it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.