java nested if statement else not working -
this question has answer here:
- java if-if-else behavior 6 answers
the else part of statement not executing when none of other statements true.
if (personplay.equals(computerplay)) system.out.println("it's tie!"); else if (personplay.equals("r")) if (computerplay.equals("s")) system.out.println("rock crushes scissors. win!!"); else if (personplay.equals("p")) if (computerplay.equals("r")) system.out.println("paper raps around rock. win!"); else if (personplay.equals("s")) if (computerplay.equals("p")) system.out.println("scissors cut paper. win!"); else system.out.println("you lose");
use brackets :
if (personplay.equals(computerplay)) { system.out.println("it's tie!"); } else if (personplay.equals("r")) { if (computerplay.equals("s")) system.out.println("rock crushes scissors. win!!"); } else if (personplay.equals("p")) { if (computerplay.equals("r")) system.out.println("paper wraps around rock. win!"); } else if (personplay.equals("s")) { if (computerplay.equals("p")) system.out.println("scissors cut paper. win!"); } else { system.out.println("you lose"); }
as mentioned in comments, code still not work, since logic flawed. should either have else clause in each internal if
, in should print "you lose" :
if (personplay.equals(computerplay)) { system.out.println("it's tie!"); } else if (personplay.equals("r")) { if (computerplay.equals("s")) system.out.println("rock crushes scissors. win!!"); else system.out.println("you lose"); } else if (personplay.equals("p")) { if (computerplay.equals("r")) system.out.println("paper wraps around rock. win!"); else system.out.println("you lose"); } else if (personplay.equals("s")) { if (computerplay.equals("p")) system.out.println("scissors cut paper. win!"); else system.out.println("you lose"); } else { system.out.println("invalid input"); }
or eliminate inner if
s , use &&
instead :
if (personplay.equals(computerplay)) { system.out.println("it's tie!"); } else if (personplay.equals("r") && computerplay.equals("s")) { system.out.println("rock crushes scissors. win!!"); } else if (personplay.equals("p") && computerplay.equals("r")) { system.out.println("paper wraps around rock. win!"); } else if (personplay.equals("s") && computerplay.equals("p")) { system.out.println("scissors cut paper. win!"); } else { system.out.println("you lose"); }
Comments
Post a Comment