public class WhileLoop
1: import java.util.Scanner;
3: /**
4: * A program to calculate the average of numbers entered by the user.
5: *
6: * @author Mark Young
7: */
8: public class WhileLoop {
10: /**
11: * Run this program.
12: *
13: * @param args command lines arguments (ignored)
14: */
15: public static void main(String[] args) {
16: // Identify myself...
17: System.out.print("\n\n\n\n\n\n\n\n\n\n"
18: + "Sample Program (Java)\n"
19: + "=====================\n\n"
20: + "Finds the average of positive integers entered by the user.\n"
21: + "Enter a negative number to stop input.\n\n\n\n");
23: // Declare and initialize variables
24: int sum = 0;
25: int count = 0;
26: int n;
28: // Get the input from the user
29: System.out.print("Enter a number: ");
30: Scanner kbd = new Scanner(System.in);
31: n = kbd.nextInt();
32: while (n >= 0) {
33: sum += n;
34: count++;
35: System.out.print("Enter a number: ");
36: n = kbd.nextInt();
37: }
39: // Print the result
40: System.out.print("\n\nAverage = "
41: + ((double)sum/(double)count)
42: + ".\n\n");
43: }
44: }