1  /*
  2   *  File:  LargestDeluxe.java
  3   *
  4   *  Exercise 2.17 on p.115 of "Java How To Program" (deluxe version):
  5   *  Find the two largest of an arbitrary number of input characters.
  6   *  To terminate input, type whatever character your operating system
  7   *  recognizes as end-of-input (control-D on UNIX or control-Z on DOS).
  8   *
  9   *  Copyright:  Northeast Parallel Architectures Center
 10   *  
 11   */
 12  
 13  import java.io.IOException;
 14  
 15  public class LargestDeluxe {
 16  
 17    // Ignore IO exceptions:
 18    public static void main ( String args[] ) throws IOException {
 19  
 20      int count = 0;                  // character counter
 21      int currChar;                   // input character
 22      int largestChar = 0;            // largest input character
 23      int nextLargestChar = 0;        // next largest input character
 24      boolean isEndOfInput = false;   // end-of-input flag
 25      boolean isControlChar;          // control character flag
 26  
 27      // Read and process characters:
 28      System.out.print( "Enter character #1: " );
 29      while ( ! isEndOfInput ) {
 30        // Read a character:
 31        currChar = System.in.read();
 32        // The read() method returns -1 if end-of-input is detected:
 33        isEndOfInput = ( currChar == -1 );
 34        if ( isEndOfInput ) {
 35          // Print newline:
 36          System.out.println( "" );
 37        } else {
 38          // Test for control character:
 39          isControlChar = ( (char) currChar < '\u0020' ) ;
 40          if ( isControlChar ) {
 41            if ( (char) currChar == '\n' ) {
 42              // Prompt for next character:
 43              System.out.print( "Enter character #" );
 44              System.out.print( (count + 1) + ": " );
 45            }
 46          } else {
 47            count++;
 48            if ( currChar > largestChar ) {
 49              nextLargestChar = largestChar;
 50              largestChar = currChar;
 51            } else if ( currChar > nextLargestChar ) {
 52              nextLargestChar = currChar;
 53            }
 54          }
 55        }
 56      } // end while loop
 57  
 58      // Output largest character(s):
 59      if ( count > 0 ) {
 60        System.out.println( "Largest = " + (char) largestChar );
 61      }
 62      if ( count > 1 ) {
 63        System.out.println( "Next largest = " + (char) nextLargestChar );
 64      }
 65  
 66    } // end main method
 67  
 68  } // end LargestDeluxe class