0

I have 2 classes: MyZoo & Animal.

With my current code, I am focusing on my method readDataFromFile() which reads tab separated text files like this:

Bird    Golden Eagle    Eddie
Mammal  Tiger   Tommy
Mammal  Lion    Leo
Bird    Parrot  Polly
Reptile Cobra   Colin

With my current scanner method, I have split each column up so that I can call individually..The issue is that the first line contains 'Golden Eagle' which are both separated by a Tab, so that the scanner picks up 'Golden Eagle as 2 separate words instead of 1 for species. The Current Output:

Bird  Golden Eagle  <---- (Missing Eddie)
Mammal  Tiger Tommy
Mammal  Lion Leo
Bird  Parrot Polly
Reptile  Cobra Colin

How would I go about using a 'useDelimiter()' method to fix this?

My Code:

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) );
       }
  • Is there a tab or a space between "Golden" and "Eagle"? – marstran Jul 14 '18 at 09:57
  • Yes, a tab separates 'Golden' and 'Eagle'. – Claira Hermitt Jul 14 '18 at 09:58
  • 1
    Then there is no way to know if the type should be "Bird Golden", or the species should be "Golden Eagle", or if the name should be "Eagle Eddie". – marstran Jul 14 '18 at 10:00
  • If the type, species and name where separated by tabs, and "Golden Eagle" were separated with a space, then you could call `scanner.useDelimiter("\t");`. – marstran Jul 14 '18 at 10:01
  • Is there not a way to have the 'Golden Eagle' to be recognised as a single substring specifically? – Claira Hermitt Jul 14 '18 at 10:01
  • You could assume that if there are 4 tokens in a line, then the two middle tokens should be joined together to be "species". But that's not quite optimal. – marstran Jul 14 '18 at 10:03
  • The problem is that you are using the delimiter character within a field. The delimiter character should be forbidden to use when it's not used as a delimiter. – marstran Jul 14 '18 at 10:06
  • using this 'scanner.useDelimiter("\\s+");' is the closest i got however the first line isn't being printed at all, but the rest of the 4 lines seem to be good.. – Claira Hermitt Jul 14 '18 at 10:12
  • @ClairaHermitt Like the other questioner in the [duplicate question](https://stackoverflow.com/q/51332008/5221149), you are mistaken. There is a **space** between `Golden` and `Eagle`, not a *tab*. – Andreas Jul 14 '18 at 10:16

0 Answers0