java嵌套if语句其他不起作用

时间:2014-09-10 15:51:24

标签: java

当其他任何陈述都不成立时,语句的else部分没有执行。

if (personPlay.equals(computerPlay))  
        System.out.println("It's a tie!");
    else if (personPlay.equals("R"))
        if (computerPlay.equals("S")) 
        System.out.println("Rock crushes scissors.  You win!!");
    else if (personPlay.equals("P"))
        if (computerPlay.equals("R")) 
        System.out.println("Paper raps around rock. You win!");
    else if (personPlay.equals("S"))
        if (computerPlay.equals("P"))
        System.out.println("Scissors cut paper. You win!");
    else 
        System.out.println("you lose");

1 个答案:

答案 0 :(得分:3)

使用括号:

if (personPlay.equals(computerPlay)) {
    System.out.println("It's a tie!");
} else if (personPlay.equals("R")) {
    if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors.  You win!!");
} else if (personPlay.equals("P")) {
    if (computerPlay.equals("R")) 
        System.out.println("Paper wraps around rock. You win!");
} else if (personPlay.equals("S")) {
    if (computerPlay.equals("P"))
        System.out.println("Scissors cut paper. You win!");
} else {
    System.out.println("you lose");
}

正如评论中所提到的,这段代码仍然无效,因为逻辑存在缺陷。您应该在每个内部if中都有一个else子句,您应该在其中打印"您将失去" :

if (personPlay.equals(computerPlay)) {
    System.out.println("It's a tie!");
} else if (personPlay.equals("R")) {
    if (computerPlay.equals("S")) 
        System.out.println("Rock crushes scissors.  You win!!");
    else 
        System.out.println("you lose");
} else if (personPlay.equals("P")) {
    if (computerPlay.equals("R")) 
        System.out.println("Paper wraps around rock. You win!");
    else 
        System.out.println("you lose");
} else if (personPlay.equals("S")) {
    if (computerPlay.equals("P"))
        System.out.println("Scissors cut paper. You win!");
    else 
        System.out.println("you lose");
} else {
    System.out.println("invalid input");
}

或者您可以消除内部if并使用&&代替:

if (personPlay.equals(computerPlay)) {
    System.out.println("It's a tie!");
} else if (personPlay.equals("R") && computerPlay.equals("S")) {
      System.out.println("Rock crushes scissors.  You win!!");
} else if (personPlay.equals("P") && computerPlay.equals("R")) { 
        System.out.println("Paper wraps around rock. You win!");
} else if (personPlay.equals("S") && computerPlay.equals("P")) {
        System.out.println("Scissors cut paper. You win!");
} else {
    System.out.println("you lose");
}