previous | start | next

Sentinel Example (cont.)

    1   import java.util.Scanner;
    2   
    3   public class SentinelInput {
    4   
    5     public static void main(String[] args) {
    6       
    7       Scanner input = new Scanner(System.in);
    8       int max = 0, n;
    9       final int SENTINEL = -1;
   10       System.out.println("This program will read integers from standard input and print " +
   11           " number of values read and the largest value.");
   12       System.out.printf("\nTo signal end of input, enter a sentinel value of -1\n\n");
   13       
   14       int count = 0;
   15       System.out.print("input value> ");
   16       n = input.nextInt();
   17       max = n;
   18       while( n != SENTINEL ) {
   19         count++;
   20         if ( n > max ) {
   21           max = n;
   22         }
   22a        n = input.nextInt();
   23       }
   24       System.out.printf("There were %d values read.\n", count);
   25       if ( count > 0 ) {
   26         System.out.printf("The maximum value read was %d\n", max);
   27       }
   28          
   29     }
   30   }


previous | start | next