ScannerDemo.java
Download ScannerDemo.java
1: // Scanner Demo, showing how to skip over bad data.
2: // In this dumb console application, you just enter a series of integers.
3: // If a non-integer is entered, we need to skip over it. The regular
4: // expression used with in.skip says to skip leading whitespace, then following
5: // non-whitespace. This is needed since the last in.nextInt left any
6: // whitespace following the number unread.
7: //
8: // Try entering in multiple items on one line. Try typing EOF (^Z or ^D).
9: // To stop, type ^C.
10: //
11: // There are better ways to write code for console input, but this technique
12: // is useful when reading from files, such as CSV data. (A better way is
13: // to read a line at a time (which won't block), and extract data from that.)
14: //
15: // Written 9/2015 by Wayne Pollock, Tampa Florida USA
16:
17: import java.util.Scanner;
18:
19: class ScannerDemo {
20: public static void main ( String [] args ) {
21: Scanner in = new Scanner( System.in );
22: System.out.print( "Enter a number (type ^C to exit): " );
23: while ( true ) {
24: if ( in.hasNextInt() ) {
25: System.out.println( "You entered " + in.nextInt() );
26: } else {
27: System.out.println( "--Skipping bad item--" );
28: in.skip( "\\s*\\S*" ); // or in.next(); // Read and skip token
29: }
30: System.out.print( "Enter a number: " );
31: }
32: }
33: }