public class JavaAverage
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 {
10: // only Scanner for System.in
11: public static final Scanner KBD = new Scanner(System.in);
13: public static void main(String[] args) {
14: // Identify myself...
15: System.out.print("\n\n\n\n\n\n\n\n\n\n"
16: + "Sample Program (Java)\n"
17: + "=====================\n\n"
18: + "Finds the average of positive integers "
19: + "entered by the user.\n"
20: + "Enter a negative number to stop input.\n\n\n\n");
22: // Declare and initialize variables
23: int sum = 0;
24: int count = 0;
25: int num;
26: double average;
28: // Get the first number from the user
29: System.out.print("Enter a number: ");
30: num = KBD.nextInt();
32: // keep going until the user enters a negative number
33: while (num >= 0) {
34: // add the last number to the sum
35: sum += num;
37: // add one to the count
38: count++;
40: // get the next number
41: System.out.print("Enter a number: ");
42: num = KBD.nextInt();
43: }
45: // Calculate the average
46: average = (double)sum / (double)count;
48: // Print the result
49: System.out.print("\n\nAverage = "
50: + average
51: + ".\n\n");
52: }
54: }