While Loops

This program finds the total of numbers that are 0 or more. This program would work for scores on a test for instance, where a negative value is not in the valid data. Entering a value less than 0 ends the loop. This value that ends the loop is called a sentinel value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Find total, count, print average 
package somePackage;
import java.util.*;
public class InchesTable {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int count=0, total=0, num;
    System.out.print("Enter number (-1 to end): ");
    num=keyboard.nextInt();
    while (num>=0) {
      total+=num;
      count++;
      System.out.print("Enter number (-1 to end): ");
      num=keyboard.nextInt();
	}//while
    System.out.println("Count="+count);
    System.out.println("Total="+total);
    if (count > 0)  // avoid dividing by zero! 
      System.out.println("Average="+1.0*total/count);
  }//main
}//class
CODE

Sample output:

Enter number (-1 to end): 6
Enter number (-1 to end): 3
Enter number (-1 to end): 9
Enter number (-1 to end): -1
Total=18

To Do:

  • Run the program in your compiler. Try different sets of numbers.
  • Enter data that will cause the value of count to be 0.

NEXT: