-2

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();
  • 1
    That is because `useDelimiter` specifies the delimiter pattern for your input. The simplest approach is to read the line and `split()` the string over `\\t`. – Marco Luzzara Jul 14 '18 at 12:03
  • 1
    This is the 6th question on the same homework your are asking and this one looks like a duplicate of the last one. Show some respect for the stackoverflow community and stop spamming with similar questions. Follow through on the questions you have already asked, and from how it looks already have good answers to, instead of constantly asking new ones. – Joakim Danielson Jul 14 '18 at 12:47
  • 1
    I'm voting to close this question as off-topic because OP is asking the same question over and over again. – Joakim Danielson Jul 14 '18 at 12:48

1 Answers1

0

First of all, the text you pasted is not tab-delimited, but multi-space delimited. Make sure the real file you're using is tab-delimited.

It seems like you could get the behavior you want with a delimiter that accepts tabs or line feeds, but not spaces. Here's an example:

try (Scanner scanner = ...) {
  scanner.useDelimiter("\\t|\\R");

  while (scanner.hasNext()) {
    String type = scanner.next();
    String species = scanner.next();
    String name = scanner.next();
    ...
  }

}

If you do this, you don't want to call nextLine.

Finn
  • 652
  • 7
  • 16