Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in line with blank space at end using java scanner class

I'm helping my sisters with a simple java program and I'm stumped. They've only learned scanner classes to read file contents, so I think they're supposed to use the scanner class. Each line contains letters and potentially a blank space, and we're hoping to store each line in an array. This works fine and dandy until one of the lines contains something like:

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

However, scanner.nextLine() seems to disregard this last blank space. I figured I could set my scanner delimiter to \n like so:

scanner.useDelimiter("\n")

and then use scanner.Next() from there, but this still doesn't seem to work. I've googled around and taken a look at a few stackoverflow questions. This question here seems to suggest this is not easily done with the scanner class: How to read whitespace with scanner.next()

Any ideas? I feel like there's an easy way I'm overlooking.

This is how I'm reading in the lines:

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

Using the above example, my string would read abcde f. It will get rid of the empty space at the end. I've also tried to use hasNext and next. Pardon my formatting, I'm editing on a phone.

like image 586
Kevin Avatar asked Aug 01 '15 01:08

Kevin


1 Answers

Save your text file as ANSI encoding and try again.

By right scanner.nextLine() will capture everything in the line, including whitespace.

scanner.next() will not capture whitespace as the delimiter is whitespace by default.

like image 124
Niko Wah Avatar answered Sep 29 '22 15:09

Niko Wah