Good day!
Below is a code that demonstrates a NESTED IF STATEMENT for exam marks:
public class NestIfExample {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
// Asking the user to input their score
System.out.print("Enter your score: ");
int score = inputDevice.nextInt();
// Outer if statement
if (score >= 50) {
System.out.println("You passed the exam!");
// Inner if statement - only checked if the score is 50 or more
if (score >= 80) {
System.out.println("Great job! You scored in the top range.");
} else {
System.out.println("Good effort, but there's room for improvement.");
}
} else {
System.out.println("Unfortunately, you did not pass. Try again next time.");
}
}
}
How do I change this NESTED IF STATEMENT to a SINGLE IF STATEMENT that has the LOGICAL &&(AND) OPERATOR and achieve the same output?
This is what I tried. I created a SINGLE IF STATEMENT by joining two comditions and making them one condition, (score >= 80 && score >=50).
I’m not sure if it’s correct. Please let me know.
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
// Asking the user to input their score
System.out.print("Enter your score: ");
int score = inputDevice.nextInt();
// Single if statement using logical AND (&&) operator
if (score >= 80 && score >= 50) {
System.out.println("You passed the exam!");
System.out.println("Great job! You scored in the top range.");
} else if (score >= 50) {
System.out.println("You passed the exam!");
} else {
System.out.println("Unfortunately, you did not pass. Try again next time.");
}
}
}
Tom Vuma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You are close, but you missed a print statement from the second condition:
// Asking the user to input their score
System.out.print("Enter your score: ");
int score = inputDevice.nextInt();
// Single if statement using logical AND (&&) operator
if (score >= 80 && score >= 50) {
System.out.println("You passed the exam!");
System.out.println("Great job! You scored in the top range.");
} else if (score >= 50) { // implicit: score < 80 for this case
System.out.println("You passed the exam!");
// only change is next line
System.out.println("Good effort, but there's room for improvement.");
} else {
System.out.println("Unfortunately, you did not pass. Try again next time.");
}