Source of ExamAverager.java


  1: //ExamAverager.java
  2: 
  3: import java.util.*;
  4: 
  5: /**
  6:  * Determines the average of a list of (nonnegative) exam scores.
  7:  * Repeats for more exams until the user says to stop.
  8:  */
  9: public class ExamAverager
 10: {
 11:     public static void main(String[] args)
 12:     {
 13:         System.out.println("This program computes the average of");
 14:         System.out.println("a list of (nonnegative) exam scores.");
 15: 
 16:         double sum;
 17:         double next;
 18:         int numberOfStudents;
 19:         String answer;
 20: 
 21:         Scanner keyboard = new Scanner(System.in);
 22:         do
 23:         {
 24:             System.out.println();
 25:             System.out.println("Enter all the scores to be averaged.");
 26:             System.out.println("Enter a negative number after");
 27:             System.out.println("you have entered all the scores.");
 28:             sum = 0;
 29:             numberOfStudents = 0;
 30:             next = keyboard.nextDouble();
 31:             while (next >= 0)
 32:             {
 33:                 sum = sum + next;
 34:                 numberOfStudents++;
 35:                 next = keyboard.nextDouble();
 36:             }
 37:             if (numberOfStudents > 0)
 38:                 System.out.println("The average is " +
 39:                     (sum / numberOfStudents));
 40:             else
 41:                 System.out.println("No scores to average.");
 42:             System.out.println("Want to average another exam?");
 43:             System.out.println("Enter yes or no.");
 44:             answer = keyboard.next();
 45:         }
 46:         while (answer.equalsIgnoreCase("yes"));
 47:     }
 48: }