previous | start | next

Example Reading Input without a Sentinel

    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;
   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, type ctrl-z (or ctrl-d)\n\n");
   13       
   14       int count = 0;
   15       System.out.print("input value> ");
   16       while( input.hasNextInt() ) {
   17         n = input.nextInt();
   18         if ( count == 0 ) {
   19            max = n;
   20         } else {
   21           if ( n > max ) {
   22             max = n;
   23           }
   24         }
   25         count++;
   26       }
   27       System.out.printf("There were %d values read.\n", count);
   28       if ( count > 0 ) {
   29         System.out.printf("The maximum value read was %d\n", max);
   30       }
   31          
   32     }
   33   }

   


previous | start | next