java - Nested if returning unreachable code -


i'm doing (pseudo) ai interface of questions , answers, 'answer' class bunch of if's statements: if "a" in message then return "b".

i want able give more depth, inserting nested if's, second if giving "unreachable code". can solve it? there better way i'm trying?

main class:

system.out.println("type message:"); string message = talkback.beginanswers(in.nextline()); 

...

beginanswers class:

public string beginanswers (string message) {  if("nothing".equalsignorecase(message)) {  return "are sure?";       if("yes".equalsignorecase(message)) {        return "ok";         }    }    ....  } 

you error because first return statement:

return "are sure?"; 

if ever reached, terminate execution of beginanswers() method & return control caller method. code after:

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

will never reached.

as solution, can take nested if statement out of first one:

if("nothing".equalsignorecase(message)) {     return "are sure?"; } else if("yes".equalsignorecase(message)) {     return "ok"; } 

you can ramp whole thing in 1 line using ternary operator, & return null if none of 2 conditions true:

return "nothing".equalsignorecase(message) ? "are sure?" :         "yes".equalsignorecase(message) ? "ok" : null; /* if message == "nothing" return "are sure?"    if message == "yes" return "ok"    if message != "yes" , message != "nothing" return null     p.s: '==' , '!=' demonstration only. keep using .equals()     method matching strings */ 

Comments