While Loops

This loops to show "pass" or "fail" for each grade.

Notice that the first value is read before the loop and each subsequent value is read as the last thing in the loop. This avoid the problem of the negative value showing "Fail".

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
27
//Input grades until a negative grade is entered, count number of passing and number failing
package grades;
import java.util.*;
public class PassFail {
  public static void main(String[] args) {
	Scanner keyboard=new Scanner(System.in); //do just once
	int grade, passCount, failCount;
	passCount = 0;
	failCount = 0;
	System.out.print("Enter grade:");;
	grade=keyboard.nextInt();
	while (grade >=0) {
	  if (grade >= 60) {
		  System.out.println("pass");
		  passCount++;
	  }//pass
	  else {
		  System.out.println("fail");
		  failCount++; 
	  }//else
	  System.out.print("Enter next grade:");;
	  grade=keyboard.nextInt();
	}//while
	System.out.println("Number of passing grades: "+passCount);
	System.out.println("Number of failing grades: "+failCount);
  }//main
}//class
CODE

Sample output:

Enter grade:80
pass
Enter next grade:60
pass
Enter next grade:90
pass
Enter next grade:0
fail
Enter next grade:-1
Number of passing grades: 3
Number of failing grades: 1

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: