Using Scanner to stop reading input on a blank line
Using the new java 1.5 Scanner class is tricky if you want it to stop reading input when it reaches a blank line. To do this, use two nested java.util.Scanner instances, one to read lines, the other to parse each line:
import java.util.*;
public class Test{
public static void main(String [] args){
Scanner s = new Scanner(System.in);
while(s.hasNextLine()){
Scanner ss = new Scanner(s.nextLine());
if(!ss.hasNext())
break;
// line empty, quit
while(ss.hasNext()){
// handle input types
ss.next();
}
ss.close();
}
System.err.println("Done program");
s.close();
}
}
That’s all there is to a complicated use of Scanner for line-by-line text tokenization!
This entry was posted on Tuesday, September 6th, 2005 at 1:30 pm and is tagged with public class test, scanner system, reading input, input types, nextline, blank line, main string, import java, java util, new java, string args, instances, ss. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback.

Add New Comment
Viewing 2 Comments
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks
(Trackback URL)