Judges.java

Download Judges.java

 1: // Judges.java - a non-GUI Java program to compute the scores of the
 2: // Figure Skating event at the Olympics.  There are five judges, and the
 3: // final score should be the average of the middle three scores.  (Scores
 4: // are integers between 0 and 10.)
 5: //
 6: // The more obvious solution (obvious to some anyway :-) is to read all the
 7: // scores into variables, or an array (or other collection), then find and
 8: // remove the smallest, then find and remove the largest, and finally
 9: // calculate the average of the three remaining scores, by summing them and
10: // dividing by three.  But, as is often the case with programs, a less obvious
11: // solution can be shorter and more efficient.  In this case we will read each
12: // score, and as we go we will track the highest and lowest score as well as
13: // the sum of all the scores.  After the last score has been read, we can just
14: // subtract the largest and smallest score from the total, and then divide
15: // by three.
16: //
17: // Special care is needed to initialize the highest and lowest scores found!
18: //
19: // Written 3/2006 Wayne Pollock, Tampa Florida USA.  All Rights Reserved.
20: 
21: import java.util.Scanner;
22: 
23: class Judges
24: {
25:    public static void main ( String [] args )
26:    {
27:       final int MIN_LEGAL_SCORE = 0, MAX_LEGAL_SCORE = 10;
28:       final int NUM_SCORES = 5;
29: 
30:       int lowScore = MAX_LEGAL_SCORE + 1;
31:       int highScore = MIN_LEGAL_SCORE - 1;
32:       int totalScore = 0;
33: 
34:       // Set up input parser:
35:       Scanner in = new Scanner( System.in );
36: 
37:       System.out.println( "Enter the " + NUM_SCORES + " Judges' scores:\n" );
38:       for ( int i = 1; i <= NUM_SCORES; ++i )
39:       {
40:             System.out.printf( "Enter score %2d: ", i );
41:             int score = in.nextInt();
42:             if ( score < MIN_LEGAL_SCORE || score > MAX_LEGAL_SCORE )
43:             {   System.err.println( "\n\t***Error: Illegal score value, " +
44:                      "please re-enter!\n" );
45:                 --i;  // Reset attempt4
46: 
47:                 continue;
48:             }
49: 
50:             if ( score < lowScore  )  lowScore  = score;
51:             if ( score > highScore )  highScore = score;
52:             totalScore += score;
53:       }
54: 
55:       // Subtract the low and high scores from the running total:
56:       totalScore -= (lowScore + highScore);
57: 
58:       // Display score, rounded to one decimal place:
59:       System.out.printf( "\n\nAnd the Judges' score is:  %.1f\n",
60:          (totalScore / 3.0) );
61:    }
62: }