Kaka
Kaka

Reputation: 151

Nested if returning unreachable code

I'm doing a (pseudo) AI interface of questions and answers, my 'answer' class is a bunch of if's statements: if "a" in message then return this "b".

I want to be able to give it more depth, by inserting nested if's, but that second if is giving "Unreachable code". What can I do to solve it? Is there a better way to do what i'm trying?

Main class:

System.out.println("Type your message:");
String message = talkback.beginAnswers(in.nextLine());

...

beginAnswers class:

public String beginAnswers (String message) {

if("nothing".equalsIgnoreCase(message)) {
 return "Are you sure?";

     if("yes".equalsIgnoreCase(message)) {
       return "ok";
        }
   }

  ....

}

Upvotes: 2

Views: 320

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

You get the error because the first return statement:

return "Are you sure?";

if ever reached, will terminate the execution of the beginAnswers() method & return control to the caller method. So the code after:

if("yes".equalsIgnoreCase(message)) {
    return "ok";
}

will never be reached.

As a solution, you can take your nested if statement out of the first one:

if("nothing".equalsIgnoreCase(message)) {
    return "Are you sure?";
}
else if("yes".equalsIgnoreCase(message)) {
    return "ok";
}

You can also ramp up the whole thing in one line using a ternary operator, & return null if none of those 2 conditions were true:

return "nothing".equalsIgnoreCase(message) ? "Are you sure?" : 
       "yes".equalsIgnoreCase(message) ? "ok" : null;
/* if message == "nothing" return "Are you sure?"
   if message == "yes" return "ok"
   if message != "yes" AND message != "nothing" return null 
   P.S: '==' and '!=' are for demonstration only. Keep using the .equals() 
   method for matching strings */

Upvotes: 3

Related Questions