简体   繁体   English

如果不满足if语句中的条件,为什么while循环中的else语句不执行?

[英]Why won't the else statement in my while loop execute when the conditions in the if statement aren't met?

I'm making a game called 'Game of Nim' in Netbeans. 我正在Netbeans中制作一个名为“尼姆游戏”的游戏。 Basically, a random amount of stones between 15-30 is generated and a computer and a player take turns taking 1-3 stones until there are none left. 基本上,会随机产生15-30颗宝石,然后计算机和玩家轮流拿1-3颗宝石,直到剩下一枚为止。 The player to take the last stones loses. 玩家拿下最后一块石头失败。 I'm coding this in a jframe form. 我正在以jframe形式对此进行编码。 I want to make sure the player doesn't enter a number bigger than 3, less than 1 and bigger than the total stones, so I made a while loop with an if statement for the input that meets the requirements and an else statement if they aren't met. 我要确保玩家输入的数字不会大于3,小于1且大于总宝石数,所以我用if语句对符合要求的输入进行了while循环,而if则进行了else循环不见面。 My problem is that when a player does enter numbers that shouldn't be entered, no error message appears and the game continues as normal. 我的问题是,当玩家输入了不应输入的数字时,不会出现错误消息,并且游戏将继续正常进行。 Here is where I think the problem is: 我认为这是问题所在:

    public int playerInput(){
        // Getting the user input and converting it into an integer
        int userIn = Integer.parseInt(txtIn.getText());
        //
        boolean input = false;

        // Do this while the input isn't between 1-3 and higher than the total amount of rocks
        while(!input){
            //
            if (userIn < 3 || userIn > 1 || userIn < totalStone){
                //
                input = true;                                      
            }
                //
                else{
                    // Output an error message
                    txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
                }   
        }
        // return the amount of rocks the user takes
        return userIn;              
}

Here is most of the code for the game (I am going to use the random slashes for commenting): 这是游戏的大多数代码(我将使用随机斜杠进行注释):

    public void computerMove() {      
    // Generating a number for the computer's move
    int comIn = (int)(Math.random() * 2) + 1;            

    // If number generated is bigger than the total stones,
    if (comIn > totalStone){           
        // Get the difference between the total and the random number
        int totalComDiff = Math.abs(totalStone - comIn);
        // Subtract the difference from the random number
        comIn -= totalComDiff;
        // Substract the rocks taken from the total
        totalStone -= comIn;
        // Display a message of the rocks taken and the rocks left
        txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
        }
            // Otherwise, if the random number is smaller than the total,
            else if (comIn < totalStone){
                // Substract the rocks taken from the total
                totalStone -= comIn;
                // Display a message of the rocks taken and the rocks left
                txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");

            }
             // If the total equals amount the computer takes,
            else if (totalStone == comIn){                    
                // Substract the rocks taken from the total
                totalStone -= comIn;
                // Display a message of the rocks taken and the rocks left
                txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");          
                // Display a message that says the player wins
                txtaOut.setText(txtaOut.getText() +"\nThere are no more stones left. The player wins!");
            }            

            // Otherwise, if the amount of stones is 0,
            else if (totalStone == 0){
                // Display an end game message
                txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
            }

}
public void playerMove(){
    // If there are no more stones left,
    if (playerInput() == totalStone){
        // Subtracting how much the player took from the total amount of rocks
        totalStone -= playerInput();
        // Displaying how many rocks were taken and how many are left
        txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");                

        // Display a message that says the computer wins
        txtaOut.setText(txtaOut.getText() + "\nThere are no more stones left. The computer wins.");
    }
        //
        else if (playerInput() != totalStone){
            // Subtracting how much the player took from the total amount of rocks
            totalStone -= playerInput();
            // Displaying how many rocks were taken and how many are left
            txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");                

        }
        //
        else if (totalStone <= 0){
            //
            txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
            }        
}
    private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {                                         
    //
    if (totalStone > 0){
        // Display how many rocks there are
        txtaOut.setText(txtaOut.getText() +"\nThere are " +totalStone +" stones.");
        // The player does their move
        playerMove();


    }

    //
    if (totalStone > 0){
        // Computer does a turn
        computerMove();
    }

        //
        else if (totalStone == 0){
            //
            txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
        }
}                                        
    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Generating another random number
    totalStone = (int)(Math.random() * 15) + 15;

    // Clearing all the textfields
    txtIn.setText("");
    txtaOut.setText("");

    // Outputting the number of starting stones
    txtaOut.setText(txtaOut.getText() +"There are " +totalStone +" stones. It's your turn.");

} 

your if needs to look like this: 您是否需要看起来像这样:

while (!input) {
    if (!(userIn < 3 && userIn > 1 && userIn < totalStone)) {
       // Output an error message
       txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
       // Prompt the user again
       userIn = Integer.parseInt(txtIn.getText());
    } else {
       input = true;
    }
}

And, it will work. 并且,它将起作用。

It is better to check if conditions are not valid first, and then if the verification is passed do the normal flow in else block. 最好先检查条件是否无效,然后再通过验证,执行else块中的常规流程。

The way you wrote it, the if condition would always be true since || 您编写它的方式,由于||,if条件将始终为true represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true. 代表“或”,因此您要询问天气userIn小于totalStone小于3或大于1或小于1,这始终是正确的。

On the other hand && represents 'and' and '!' 另一方面,&&表示“ and”和“!” represents not. 代表不是。 So, you basically want all the conditions to be fulfilled and checking if they aren't by putting them into the brackets and putting ! 因此,您基本上希望所有条件都得到满足,并通过将其放在方括号中并放入!来检查是否不满足条件。 (negation) in front (否定)在前面

You also need to prompt the user again if the condition is not met. 如果不符合条件,还需要再次提示用户。 Otherwise it's gonna run forever and freeze the ui. 否则它将永远运行并冻结ui。

If the user enters an incorrect number, they should then be prompted to enter a new one. 如果用户输入了错误的数字,则应提示他们输入一个新的数字。 In your code, it will be stuck in the loop forever. 在您的代码中,它将永远停留在循环中。

You should also be checking that all conditions are satisfied using &&. 您还应该使用&&检查是否满足所有条件。 You need a number that is (<=3) AND (>=1) AND (<=totalStones) 您需要的数字是(<= 3)AND(> = 1)AND(<= totalStones)

public int playerInput () {

    int userIn;

    do {

        System.out.println("Enter a number between 1 - 3 and less than the amount of stones left.")

        userIn = Integer.parseInt (txtIn.getText ());

    } while (!(userIn <= 3 && userIn >= 1 && userIn <= totalStone));

This will continue to loop while the conditions are not satisfied. 当不满足条件时,它将继续循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 else语句不会在if else语句中执行 - else statements won't execute in an if else statement 为什么这个&#39;if&#39;语句不会在while循环中运行而没有其他东西也会在while循环中运行? - Why won't this 'if' statement run in a while loop without something else also happening in the while loop? 为什么我的数组不满足这个 if 语句的条件? - Why won't my array satisfy the conditions of this if-statement? 为什么我的 IF-ELSE-IF 语句不能正常工作? - Why won't my IF-ELSE-IF statement work correctly? 为什么我的循环总是通过,即使条件并不总是满足? - Why does my loop always go through even though the conditions aren't always met? 如果不满足条件且没有其他语句,则for循环中的嵌套if语句会发生什么情况? - What happens to a nested if statement in a for-loop if the conditions are not met and there is no else statement? 为什么我的 else 语句在 JAVA 中以“while 循环”执行但不在“for 循环”中执行 - Why does my else statement execute in a 'while-loop' but does not execute in a 'for-loop' in JAVA else if 语句在我放入 while 循环时不起作用 - else if statement doesn't work when i put it in while loop java While循环语句将继续循环,但不会包含我的退出循环的语句 - java While-loop statement will continue to loop but won't include my statement to exit the loop 为什么我的驱动程序不执行 while 循环? - Why won't my Driver execute the while loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM