The if-then-else
control flow statement adds a secondary path to the if statement when the expression evaluates to false
. When it evaluates to false
the else
block will be executed.
Below is the program that takes input of user test score and evaluates the score to get the corresponding grade.
package org.kodejava.basic;
import java.io.Console;
public class IfThenElseDemo {
public static void main(String[] args) {
System.out.print("Please enter your score: ");
try {
// Get an instance of system console for taking user
// input.
Console console = System.console();
// Take user score input and convert the input value into
// number.
int score = Integer.parseInt(console.readLine());
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 60) {
grade = "C";
} else if (score >= 50) {
grade = "D";
} else {
grade = "F";
}
System.out.println("Grade = " + grade);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
When the program executed you’ll need to input the test score and the program will give you the grade.
Please enter your score: 75
Grade = C
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024