简体   繁体   中英

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. 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. The player to take the last stones loses. I'm coding this in a jframe form. 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. 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.

The way you wrote it, the if condition would always be true since || represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true.

On the other hand && represents '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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM