if / else statements

To print a letter grade, we need to consider 5 possible grades. In this example, we test for each letter grade.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package grades;
import java.util.*;
public class Grades {
	public static void main(String[] args) {
		Scanner keyboard=new Scanner(System.in); //do just once
		int grade;
		char letterGrade='F';
		System.out.print("Enter your numeric grade:");
		grade=keyboard.nextInt();
		if (grade < 65) letterGrade='F';
		if(grade>=65 && grade<70) letterGrade='D';
		if(grade>=70 && grade<80) letterGrade='C';
		if(grade>=80 && grade<90) letterGrade='B';
		if (grade >= 90) letterGrade='A';
		System.out.println("The letter grade is "+letterGrade);
	}//main
}//class
CODE

SAmple Output:

Enter your numeric grade:80
The letter grade is B

Enter your numeric grade:64
The letter grade is F

When you test a program like this, you do not need to test every possible grade from 0 to 100, but you should test each Boolean expression. The following values would be good test data: 64,65,69,70,71,79,80,81,90,91.

Notice that instead of printing the grade after the if, we assign it to a variable. We print just once at the end. This makes it easier to change the wording.

NEXT: