In the program, no errors. PASS, CLEARED user inputs are working as desired. But when I enter NO as user input in the nested if, control picks "else statement" correctly, but also it is going inside, and executing the next S.O.P display like "Have you CLEARED second level of interview?" which is not required when the first level interview is not cleared. Hence, it displays both else & next if related statement. But I wanted to get displayed only else statement and get exit.
package controlStatements;
import java.util.Scanner;
class nested_if_else_Statement {
static public void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Online Assesment, enter PASS or FAIL?");
String oa = scan.nextLine();
if (oa.equals("PASS")) {
System.out.println("Please wait in the office lobby for further levels of interview.");
System.out.println("Have you CLEARED first level of interview?");
String level1 = scan.nextLine();
if(level1.equals("CLEARED")) {
System.out.println("Please wait for second level of interview.");
}else {
System.out.println("We're Sorry, better luck next time.");
}
System.out.println("Have you CLEARED second level of interview?");
String level2 = scan.nextLine();
if(level2.equals("CLEARED")) {
System.out.println("Please wait for third level of interview.");
}else {
System.out.println("We're sorry, better luck next time.");
}
System.out.println("Have you CLEARED third level of interview?");
String level3 = scan.nextLine();
if(level3.equals("CLEARED")) {
System.out.println("Please wait for fourth level of interview.");
}else {
System.out.println("We're sorry, better luck next time.");
}
System.out.println("Have you CLEARED fourth level of interview?");
String level4 = scan.nextLine();
if(level4.equals("CLEARED")) {
System.out.println("Kindly wait for final level of HR Interview.");
System.out.println("Thank you for your patience.");
}else {
System.out.println("We're sorry, better luck next time.");
}
System.out.println("Have you DONE with your HR Interview?");
String levelHR = scan.nextLine();
if(levelHR.equals("DONE")) {
System.out.println("Please wait in the office lobby, will get back shortly.");
}
} else {
System.out.println("We're Sorry, better luck next time");
}
scan.close();
}
}
These statements are working as expected. It captures the else
, but you never tell it to stop running, so it continues to the next step. An easy way to fix this is to add a return
statement whenever you want to exit the code.
if (/* whatever */) {
// do stuff
} else {
// do stuff
return;
}
// other stuff that won't be ran if `return` is reached