简体   繁体   中英

JAVA number guessing game using methods: method for play again does not work properly

I am new to JAVA and have written a program to figure out a number chosen by a human user between 1 to 100.

The program runs like it should by guessing the midpoint of the lower and upper bounds with user response of higher or lower until the correct number is guessed. However, when the program asks if you would like to play again? (y/n): it doesn't not input the char correctly. no matter what char is entered the program will run again and does not terminal on input of "n".

Any help will be greatly appreciated. Thank you!

import java.util.Scanner;

public class NumberGuesser 
{

    public static void main(String[] args)
    {
        do
        {
            playOneGame();
        }
        while(shouldPlayAgain());
    }

    //method for complete guessing number game between 1 and 100
    public static void playOneGame()
    {
        //initial lower range to 0 and upper range to 100
        int lowerBound = 0;
        int upperBound = 100;

        //Display message for user to guess a nummber
        System.out.println("Guess a number between 1 and 100.");

        //declare variables for program's number guess and user's response if number is higher or lower
        int guess;
        char userResponse;

        do //do while loop to make number guesses until correct number is found
        {
            //call method to guess midpoint number
            guess = Midpoint(lowerBound,upperBound);

            // call method to get response from user if number is high low or correct
            userResponse = getUserResponseToGuess(guess);

            //decision structure if-else statements to set new lower/upper bounds after every iteration 
            if (userResponse == 'h' || userResponse == 'H')
            {
                lowerBound = guess;
            }else if (userResponse == 'l' || userResponse == 'L')
            {
                upperBound = guess;
            }else if (userResponse == 'c' || userResponse == 'C')
            {
                shouldPlayAgain();
                playOneGame();
            }

        }while(userResponse != 'c' || userResponse != 'C');

    }

    //method to ask and allow user if they would like to play the game again
    public static boolean shouldPlayAgain()
    {
        //Prompt User if they would like to play again
        System.out.print("Great! Would you like to play again? (y/n): ");

        //Read in a character
        Scanner input = new Scanner(System.in);
        char value = input.next().charAt(0);

        //if true return y char
        return value == 'y' || value == 'Y';
    }

    //method to get response from user for computer to guess if number is high, low, or correct
    public static char getUserResponseToGuess(int guess)
    {
        //char response = guess;
        Scanner input = new Scanner(System.in);

        //declare local variable for user's response
        char response;

        do
        {
            //print out message with guess number and take input of h/l/c
            System.out.print("Is the number " + guess + "? (h/l/c): ");

            //Read in character
            response = input.next().charAt(0);

        }while(response != 'h' && response != 'l' && response != 'c'); //display guess and get user input while input does not equal h/l/c

        return response;
    }

    //method to find the midpoint from two integers. take smaller number if 2 to return with 2 integers
    public static int Midpoint(int low, int high)
    {
        int midpoint; //midpoint is a local variable

        midpoint = (high+low)/2; //compute midpoint between upper and lower bounds

        return midpoint;
    }
}

The problem is here:

        }else if (userResponse == 'c' || userResponse == 'C')
        {
            shouldPlayAgain();
            playOneGame();
        }

You ask if the player wants to go another round and then... do nothing about it and run another round anyways. try this:

        {
            if(shouldPlayAgain()){
                playOneGame();
            }
        }

You call shouldPlayAgain() without using the return value.

         if (shouldPlayAgain()){
            playOneGame();
          }

You are iterating with no exit condition in your code, when you write this code:

else if (userResponse == 'c' || userResponse == 'C')
            {
                shouldPlayAgain();
                playOneGame();

            }

You can write:

else if (userResponse == 'c' || userResponse == 'C') { break; }

then you return the control to main loop.

Regards,

Try running the below code. I've tried to modulate your code which includes conditions improvements and loop removals.

package test;

import java.util.Scanner;

public class NumberGuesser 
{

    public static void main(String[] args)
    {
/*Reduntant loop removal by codechef*/        
//        do
//        {
            playOneGame();
//        }
//        while(/*shouldPlayAgain()*/false);
    }

    //method for complete guessing number game between 1 and 100
    public static void playOneGame()
    {
        //initial lower range to 0 and upper range to 100
        int lowerBound = 0;
        int upperBound = 100;

        //Display message for user to guess a nummber
        System.out.println("Guess a number between 1 and 100.");

        //declare variables for program's number guess and user's response if number is higher or lower
        int guess;
        char userResponse;
         boolean temp = true;
         one :do //do while loop to make number guesses until correct number is found
        {
            //call method to guess midpoint number
            guess = Midpoint(lowerBound,upperBound);

            // call method to get response from user if number is high low or correct
            userResponse = getUserResponseToGuess(guess);

            //decision structure if-else statements to set new lower/upper bounds after every iteration 
            if (userResponse == 'h' || userResponse == 'H')
            {
                lowerBound = guess;
            }else if (userResponse == 'l' || userResponse == 'L')
            {
                upperBound = guess;
            }else if (userResponse == 'c' || userResponse == 'C')
            {
                /* Block restructured by codechef */
                temp = shouldPlayAgain();
                if(temp)
                {
                    System.out.println("TEMP : "+temp);
                    //playOneGame();
                    continue one;
                }else{
                    System.out.println("Breaking Loop");
                    break one;
                }
            }
            /*condition restructured by codechef*/
        }while((userResponse != 'c' || userResponse != 'C' )&& temp);

    }

    //method to ask and allow user if they would like to play the game again
    public static boolean shouldPlayAgain()
    {
        //Prompt User if they would like to play again
        System.out.print("Great! Would you like to play again? (y/n): ");

        //Read in a character
        Scanner input = new Scanner(System.in);
        char value = input.next().charAt(0);

        //if true return y char
        /* statement restructured by codechef */
        return (value=='y'||value=='Y')?true:false;
    }

    //method to get response from user for computer to guess if number is high, low, or correct
    public static char getUserResponseToGuess(int guess)
    {
        //char response = guess;
        Scanner input = new Scanner(System.in);

        //declare local variable for user's response
        char response;
/* Reduntant While loop removal by codechef*/
//        do
//        {
            //print out message with guess number and take input of h/l/c
            System.out.print("Is the number " + guess + "? (h/l/c): ");

            //Read in character
            response = input.next().charAt(0);
            System.out.println("RESONSE : "+response);
//        }while(response != 'h' && response != 'l' && response != 'c'); //display guess and get user input while input does not equal h/l/c

        return response;
    }

    //method to find the midpoint from two integers. take smaller number if 2 to return with 2 integers
    public static int Midpoint(int low, int high)
    {
        int midpoint; //midpoint is a local variable

        midpoint = (high+low)/2; //compute midpoint between upper and lower bounds

        return midpoint;
    }
}

output:-

run:

Guess a number between 1 and 100.

Is the number 50? (h/l/c): l

RESONSE : l

Is the number 25? (h/l/c): c

RESONSE : c

Great! Would you like to play again? (y/n): y

TEMP : true

Is the number 25? (h/l/c): c

RESONSE : c

Great! Would you like to play again? (y/n): n

Breaking Loop

For changes read the comments added. Hope this helps.

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