Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting a .nextLine() Scanner

Tags:

java

I am a rank amateur when it comes to Java, so please pardon my question if it seems dumb :-P I have the following code which is designed to count the number of lines in a file:

while (scanNumOfLines.hasNextLine())    
    {
    NumOfLines ++;
    scanNumOfLines.nextLine();
    }
    System.out.println("NumOfLines = "+NumOfLines);

So it counts fine, but I want to re-use the scanner for another purpose, but the nextLine has moved to the last line of the file, and I want to reset it back to the first line.

(Instead, I had to use another scanner for the other purpose, and to me this seems less elegant than it should be.)

I'm sure there must be a scanner method that resets the counter to zero?

Thanks

CJ

like image 659
user1921628 Avatar asked Dec 21 '12 13:12

user1921628


People also ask

What does scanner reset () do?

The reset() method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed. A scanning operation may block waiting for input.

Which scanner class method that resets the scanner?

The reset() method of Java Scanner class is used to reset the Scanner which are in using.

How do I clear the scanner buffer?

nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line. You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream. in = new Scanner(System.in);


1 Answers

This is impossible to do.

The reason to not include it, is the wide range of input types it supports. One example is streams. These don't store the results after they have been passed on, so they don't support resetting.

So the elegant way is to create a new Scanner. If you give it many custom settings, create a factory method.

like image 179
Thirler Avatar answered Oct 14 '22 20:10

Thirler