Source of JavaAverage.java


  1: import java.util.Scanner;

  3: /**
  4:  * A program to calculate the average of numbers entered by the user.
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class JavaAverage {
  9:     public static void main(String[] args) {
 10:         // Identify myself...
 11:         System.out.print("\n\n\n\n\n\n\n\n\n\n"
 12:                 + "Sample Program (Java)\n"
 13:                 + "=====================\n\n"
 14:                 + "Finds the average of positive integers "
 15:                 + "entered by the user.\n"
 16:                 + "Enter a negative number to stop input.\n\n\n\n");

 18:         // Declare and initialize variables
 19:         Scanner kbd = new Scanner(System.in);
 20:         int sum = 0;
 21:         int count = 0;
 22:         int n;

 24:         // Get the first number from the user
 25:         System.out.print("Enter a number: ");
 26:         n = kbd.nextInt();

 28:         // keep going until the user entered a negative number
 29:         while (n >= 0) {
 30:             // add the last number to the sum
 31:             sum += n;

 33:             // add one to the count
 34:             count++;

 36:             // get the next number
 37:             System.out.print("Enter another number or -1 to quit: ");
 38:             n = kbd.nextInt();
 39:         }

 41:         // Print the result
 42:         System.out.print("\n\nAverage = "
 43:                 + ((double)sum/(double)count)
 44:                 + ".\n\n");
 45:     }

 47: }