如何获取方法来识别if语句的其他部分?

时间:2017-09-22 21:10:49

标签: java if-statement

我做了一个街头掷骰子游戏,并在开始时有一个错误检查器以确保输入有效,我把它放在一个if语句中,然后将其余的代码(用于有效输入)作为else但是当用户输入有效数字时,它无法识别else部分。

public void play() { //method
    System.out.println("Please pick a number.");
    guess = scan.nextInt();
    if (guess == 7 || guess == 1 || guess == 0 || guess > 12) {
        System.out.println("Sorry, that is an invalid input, please choose another number.");
        guess = scan.nextInt();
    } else {
        int roll = dieOne.roll();
        int roll2 = dieTwo.roll();
        int rollSums = roll + roll2;
        System.out.println(roll + "+" + roll2);
        while (rollSums != 7) {
            if (guess == rollSums) {
                System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!");
                rollSums = 7;
                guess = 7;
            } else {
                roll = dieOne.roll();
                roll2 = dieTwo.roll();
                rollSums = roll + roll2;
                System.out.println(roll + "+" + roll2);
            }
        }
        if (rollSums != guess) {
            System.out.println("Sorry, your number was not rolled before a seven was rolled.");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我想你要执行if部分直到if条件不满足,然后你想执行else部分。如果这是你想要的,你需要将while部分作为while循环执行,而else部分作为while循环之后的代码执行。

答案 1 :(得分:0)

您需要一个while循环来确保首先获得良好的输入,然后执行游戏逻辑,如下所示:

    int guess = scan.nextInt();
    while (guess == 7 || guess == 1 || guess == 0 || guess > 12){
        System.out.println("Sorry, that is an invalid input, please choose another number.");
        guess = scan.nextInt();
    } 

    //Game Logic (Stuff in else section)