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. |

Thanks a ton for the code, saved me a lot of trouble
Thanks
thx a lot, discovered this a bit too late, but still great to know why my scanner input didnt work for blank lines.
another computer science project saved thanks to this code. cheers!
Oh god, this saved me on a computer science project. I had to edit it quite a bit to fit my application. Thanks for the insight!