// This version uses a do-while loop. public class SpaceInvadersDoWhile { 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)"); do { score = SavitchIn.readLineInt(); // Update min and max scores // We need to check if score is -1 because we don't // want it to count as a "min" score // Note: you don't have to do this in the while loop version! // (Why?) if ((score != -1) && (score < minScore || minScore == -1)) { minScore = score; } if (score > maxScore || maxScore == -1) { maxScore = score; } // Update variables so we can calculate average later. // Again, we need to check if score is -1, because // we don't want to count that one. if (score != -1) { numScores++; sumScores += score; } } while (score != -1); // terminate when sentinel value is given // 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); } }