My readDataFromFile() method reads text files like this:
Bird Golden Eagle Eddie
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
With my current while loop
, it separates each column: type, species and name
.
However the first line has 'Golden Eagle' separated by a space
not a tab
, so it counts as 2 different substrings, so the output would be 'Golden Eagle Eddie'
instead of 'Bird Golden Eagle Eddie'
.
To try fix this I used the scanner.useDelimiter("\\t");
however the output comes out like this:
Golden Eagle Eddie
Mammal Tiger
Mammal Lion Leo
Bird
Reptile Cobra Colin
with an ERROR which highlights this line in my code 'scanner.nextLine();'
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at MyZoo.readDataFromFile(MyZoo.java:72)
My Code:
scanner.useDelimiter("\\t");
scanner.next();
while(scanner.hasNextLine())
{
String type = scanner.next();
String species = scanner.next();
String name = scanner.next();
System.out.println(type + " " + species + " " + name);
scanner.nextLine();
addAnimal( new Animal(species, name, this) );
}
scanner.close();