Elliott C. Back: Technology FTW!

Using Scanner to stop reading input on a blank line

Posted in Code, Computers & Technology, Education, Java by Elliott Back on September 6th, 2005.

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.

Viewing 2 Comments

 

Trackbacks

(Trackback URL)

close Reblog this comment
blog comments powered by Disqus