Read according to space at the end using java scanner class

I help my sisters with a simple java program, and I'm at a dead end. They only studied the scanner classes to read the contents of the file, so I think they should use the scanner class. Each row contains letters and potentially empty space, and we hope to keep each row in an array. This works fine and dandy, until one of the lines contains something like:

abcde f (the space after f should be read as part of the line).

However, scanner.nextLine() does not seem to take this last empty space into account. I decided that I could set the scanner delimiter to \n as follows:

 scanner.useDelimiter("\n") 

and then use scanner.Next() , but that still doesn't work. I googled around and looked at a few stackoverflow questions. This question here seems to suggest that this is not easy to do with the scanner class: How to read spaces with the .next () scanner

Any ideas? I feel that there is an easy way with which I do not pay attention.

This is how I read the lines:

 While(scanner.hasNextLine(){ String nextLine = scanner.nextLine(); 

Using the above example, my line will read abcde f . He will get rid of the empty space at the end. I also tried using hasNext and next . Forgive my formatting, I am editing on the phone.

+6
source share
1 answer

Save the text file as ANSI encoding and try again.

By right, scanner.nextLine() will write everything in a string, including spaces.

scanner.next() will not write spaces, since the delimiter is a space by default.

+2
source

All Articles