While Loops

In this program there are no values that are outside the valid data. We must ask each time if there are more values.

Notice that we check if the answer is either 'Y' or 'y'. We do not use and because no character can be both 'y' AND 'Y'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Find total, count, print average while 'Y' loop
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;
    String answer;
    System.out.print("Are there any numbers (Y or N):");
    answer=keyboard.next();
    char ch=answer.charAt(0);
    while (ch=='Y' || ch=='y') {
      System.out.print("Enter number: ");
      num=keyboard.nextInt();
      total+=num;
      count++;
      System.out.print("Are there more numbers (Y or N):");
      answer=keyboard.next();
      ch=answer.charAt(0);
    }//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

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.
  • What values can end the loop?

NEXT: