/* * File: LargestDeluxe.java * * Exercise 2.17 on p.115 of "Java How To Program" (deluxe version): * Find the two largest of an arbitrary number of input characters. * To terminate input, type whatever character your operating system * recognizes as end-of-input (control-D on UNIX or control-Z on DOS). * * Copyright: Northeast Parallel Architectures Center * */ import java.io.IOException; public class LargestDeluxe { // Ignore IO exceptions: public static void main ( String args[] ) throws IOException { int count = 0; // character counter int currChar; // input character int largestChar = 0; // largest input character int nextLargestChar = 0; // next largest input character boolean isEndOfInput = false; // end-of-input flag boolean isControlChar; // control character flag // Read and process characters: System.out.print( "Enter character #1: " ); while ( ! isEndOfInput ) { // Read a character: currChar = System.in.read(); // The read() method returns -1 if end-of-input is detected: isEndOfInput = ( currChar == -1 ); if ( isEndOfInput ) { // Print newline: System.out.println( "" ); } else { // Test for control character: isControlChar = ( (char) currChar < '\u0020' ) ; if ( isControlChar ) { if ( (char) currChar == '\n' ) { // Prompt for next character: System.out.print( "Enter character #" ); System.out.print( (count + 1) + ": " ); } } else { count++; if ( currChar > largestChar ) { nextLargestChar = largestChar; largestChar = currChar; } else if ( currChar > nextLargestChar ) { nextLargestChar = currChar; } } } } // end while loop // Output largest character(s): if ( count > 0 ) { System.out.println( "Largest = " + (char) largestChar ); } if ( count > 1 ) { System.out.println( "Next largest = " + (char) nextLargestChar ); } } // end main method } // end LargestDeluxe class