if / else statements

Sometimes we need to nest successive if/else statements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Print the letter grade
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=' ';
		System.out.print("Enter your numeric grade:");
		grade=keyboard.nextInt();
		if (grade < 65) letterGrade='F';
		else if(grade<70) letterGrade='D';
		else if(grade<80) letterGrade='C';
		else if(grade<90) letterGrade='B';
		else letterGrade='A';
		System.out.println("The letter grade is "+letterGrade);
	}//main
}//class
CODE

This is a more efficient program. Once one of the Boolean expressions is true, all of the nested else statements are skipped.

NEXT: