// This version uses a while loop. public class SpaceInvadersWhile { public static void main(String args[]) { // Use invalid values for min and max so // we know they need to be updated with the first number int minScore = -1; int maxScore = -1; // To calculate average, we need the sum of scores and // how many were entered. double avgScore = 0; int sumScores = 0; int numScores = 0; int score; System.out.println("Please enter your Space Invaders scores " + "(-1 to terminate)"); score = SavitchIn.readLineInt(); // Other choices possible for the loop condition. // This one makes it clear what the sentinel value is (-1). while (score != -1) { // Update min and max scores if (score < minScore || minScore == -1) { minScore = score; } if (score > maxScore || maxScore == -1) { maxScore = score; } // Update variables so we can calculate average later. numScores++; sumScores += score; // Read in a new score score = SavitchIn.readLineInt(); } // Calculate the average. // Let's cast to a double so that the result is a double // (floating point division) avgScore = sumScores / (double)numScores; // Output stats System.out.println("Your highest score was " + maxScore); System.out.println("Your lowest score was " + minScore); System.out.println("Your average score was " + avgScore); } }