if-else Rock Paper Scissors Game

时间:2015-09-18 19:48:05

标签: java if-statement

我看不出为什么我的程序会终止。例如,如果我说用户输入是摇滚,它有时会说明它的平局或没有任何事情发生/终止。我尝试在不同的类区域中运行它的一些部分,但是当我输入一个值时,它不会在if / else语句中输出我想要的结果。 我知道计算机选择和用户输入代码是正确的。我相信这是if / else我搞砸了。如果我错了,请纠正我。

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int compVal = (int) (3*Math.random()) +1;
    char compChoice;
    if (compVal == 1) {
        compChoice = 'R';
    } else if (compVal == 2) {
        compChoice = 'P';
    } else {
        compChoice = 'S';
    }
    System.out.println("Rock, Paper, Scissors-Enter a choice R/P/S: ");
    String mine = keyboard.nextLine();
    char myChoice = mine.charAt(0);
    myChoice = Character.toUpperCase(myChoice);
    if (myChoice == (compChoice)) {
        System.out.println("We both chose the same item-try again");
    } else if (myChoice == ('R')) {
        if (compChoice == 'P') {
            System.out.println("I chose Paper and you chose Rock: Paper covers rock, so I win");
        }
    } else if (myChoice == ('R')) {
        if (compChoice == ('S')) {
            System.out.println("I chose Scissors and you choise Rock: Rock breaks Scissors, so you win");
        }
    } else if (myChoice == ('P')) {
        if (compChoice == ('S')) {
            System.out.println("I chose Scissors and you chose Paper: Scissors cuts Paper, so I win");
        }
    } else if (myChoice == ('P')) {
        if (compChoice == ('R')) {
            System.out.println("I chose Rock and you chose Paper: Paper covers Rock, so you win");
        }
    } else if (myChoice == ('S')) {
        if (compChoice == ('P')) {
            System.out.println("I chose Paper and you chose Scissors: Scissors cuts Paper, so you win");
        }
    } else if (myChoice == ('S')) {
        if (compChoice == ('R')) {
            System.out.println("I chose Rock and you chose Scissors: Rock breaks Scissors, so I win");
        }
    }
} 

1 个答案:

答案 0 :(得分:3)

你有多个永远无法执行的if / else语句。

考虑这段代码

if (myChoice == ('R')) {
    if (compChoice == 'P') {
        System.out.println("I chose Paper and you chose Rock: Paper covers rock, so I win");
    }
} else if (myChoice == ('R')) { // this will ONLY execute if the previous if statement is false.

每秒if子句都无法执行,因为您已经检查过该条件。即,选择不能是R,因为如果它是,它将执行前一个块。最简单的解决方案是删除重复项,因为您不需要它们。

} else if (myChoice == ('R')) {
    if (compChoice == 'P') {
        System.out.println("I chose Paper and you chose Rock: Paper covers rock, so I win");
    }
    if (compChoice == ('S')) {
        System.out.println("I chose Scissors and you choise Rock: Rock breaks Scissors, so you win");
    }

甚至

} else if (myChoice == 'R') {
    if (compChoice == 'P') 
        System.out.println("I chose Paper and you chose Rock: Paper covers rock, so I win");
    else
        System.out.println("I chose Scissors and you choise Rock: Rock breaks Scissors, so you win");
} else