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