// Judges.java - a non-GUI Java program to compute the scores of the // Figure Skating event at the Olympics. There are five judges, and the // final score should be the average of the middle three scores. (Scores // are integers between 0 and 10.) // // The more obvious solution (obvious to some anyway :-) is to read all the // scores into variables, or an array (or other collection), then find and // remove the smallest, then find and remove the largest, and finally // calculate the average of the three remaining scores, by summing them and // dividing by three. But, as is often the case with programs, a less obvious // solution can be shorter and more efficient. In this case we will read each // score, and as we go we will track the highest and lowest score as well as // the sum of all the scores. After the last score has been read, we can just // subtract the largest and smallest score from the total, and then divide // by three. // // Special care is needed to initialize the highest and lowest scores found! // // Written 3/2006 Wayne Pollock, Tampa Florida USA. All Rights Reserved. import java.util.Scanner; class Judges { public static void main ( String [] args ) { final int MIN_LEGAL_SCORE = 0, MAX_LEGAL_SCORE = 10; final int NUM_SCORES = 5; int lowScore = MAX_LEGAL_SCORE + 1; int highScore = MIN_LEGAL_SCORE - 1; int totalScore = 0; // Set up input parser: Scanner in = new Scanner( System.in ); System.out.println( "Enter the " + NUM_SCORES + " Judges' scores:\n" ); for ( int i = 1; i <= NUM_SCORES; ++i ) { System.out.printf( "Enter score %2d: ", i ); int score = in.nextInt(); if ( score < MIN_LEGAL_SCORE || score > MAX_LEGAL_SCORE ) { System.err.println( "\n\t***Error: Illegal score value, " + "please re-enter!\n" ); --i; // Reset attempt4 continue; } if ( score < lowScore ) lowScore = score; if ( score > highScore ) highScore = score; totalScore += score; } // Subtract the low and high scores from the running total: totalScore -= (lowScore + highScore); // Display score, rounded to one decimal place: System.out.printf( "\n\nAnd the Judges' score is: %.1f\n", (totalScore / 3.0) ); } }