0

I'm trying to save words, their parts of speeches, and definitions to a file when I exit the code and then read them back when I reopen the code the next time. This is my save line:

WordListPrinter.println(name + " " + partOfSpeech + " " + definition);

This is my read code

while(readFromFile.hasNextLine()){
            String name = readFromFile.next();
            String POS = readFromFile.next();
            String definition = readFromFile.nextLine();
}

Each time I run the code, it adds a space to definition, because the String definition = readFromFile.nextLine(); part reads the " " + definition from the save line. I tried

while(readFromFile.hasNextLine()){
            String name = readFromFile.next();
            String POS = readFromFile.next();
            String useless = readFromFile.next();
            String definition = readFromFile.nextLine();
}

to get rid of the space, but it removed the space and the first word of the definition. I also tried char useless = readFromFile.next().charAt(0);, but that just saved the space to useless and removed the first word of the definition anyways. Is there a way for me to scan and remove the space without removing the first word?

AntiExator
  • 21
  • 4

1 Answers1

0

The "problem" comes from mixing next() with nextLine() invocations, and is "expected behavior". (javadoc)

To get rid of the blank:

  • You could (if applicable) consistently us next() (without nextLine()) , so:

    String definition = readFromFile.next();
    
  • String.trim is "never wrong" (to remove trailing white space from a string):

    String definition = readFromFile.nextLine().trim();
    
xerx593
  • 12,237
  • 5
  • 33
  • 64