简体   繁体   English

JAVA号码猜谜游戏使用方法:再次玩的方法无法正常工作

[英]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. 我是JAVA的新手,并编写了一个程序来计算人类用户在1到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. (y / n):输入的字符不正确。 no matter what char is entered the program will run again and does not terminal on input of "n". 无论输入什么字符,程序都将再次运行,并且不会在输入“ 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. 您可以不使用返回值而调用shouldPlayAgain()

         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. 猜一个介于1到100之间的数字。

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

RESONSE : l 回应:l

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

RESONSE : c 响应:c

Great! 大! Would you like to play again? 您想再玩一次吗? (y/n): y (y / n):y

TEMP : true TEMP:真

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

RESONSE : c 响应:c

Great! 大! Would you like to play again? 您想再玩一次吗? (y/n): n (y / n):n

Breaking Loop 断环

For changes read the comments added. 对于更改,请阅读添加的注释。 Hope this helps. 希望这可以帮助。

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

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