ScannerDemo2.java
Download ScannerDemo2.java
1: // Scanner Demo 2, showing how to skip over bad data.
2: // In this dumb console application, you just enter a series of integers,
3: // one per line. These are summed and the total displayed at the end.
4: //
5: // Try entering in multiple items on one line. Type EOF (^Z or ^D) or ^C
6: // to exit the while loop. For error control, use hasNext(pattern) to ensure
7: // each line only contains a single number.
8: //
9: // Written 9/2015 by Wayne Pollock, Tampa Florida USA
10:
11: import java.util.Scanner;
12:
13: class ScannerDemo2 {
14: public static void main ( String [] args ) {
15: Scanner in = new Scanner( System.in );
16: int total = 0;
17: System.out.print( "\nEnter a number (type ^Z to exit): " );
18: while ( in.hasNextLine() ) {
19: Scanner s = new Scanner( in.nextLine() );
20: if ( s.hasNextInt() ) {
21: int num = s.nextInt();
22: total += num;
23: System.out.println( "You entered " + num );
24: } else {
25: System.out.println( "--Skipping bad item--" );
26: }
27: System.out.print( "Enter a number: " );
28: }
29: System.out.println( "\nTotal: " + total );
30: }
31: }