Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

java - Resetting a .nextLine() Scanner

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...