简体   繁体   English

Java 做猜谜游戏

[英]Java do while Guessing Game

So for an assignment I had to do last week I had to make a guessing game in Java using 4 do-while loops and if statements.因此,对于上周我必须完成的一项作业,我必须使用 4 个 do-while 循环和 if 语句在 Java 中制作一个猜谜游戏。 I was unable to complete it successfully and the class has moved on providing me no help.我无法成功完成它,班级继续前进,没有提供任何帮助。 I would appreciate it if someone could look at my code and tell me where I could improve it so the program works properly.如果有人可以查看我的代码并告诉我我可以在哪里改进它以便程序正常运行,我将不胜感激。

To give a brief description of the assignment, the assignment calls for 4 do-while loops:为了简要描述赋值,赋值需要 4 个 do-while 循环:

  1. The primary do-while loop which contains most of the code and keeps the program running until the user wants to quit主要的 do-while 循环,它包含大部分代码并保持程序运行直到用户想要退出
  2. The game do-while loop which keeps the game running until the user guesses the correct number, at which point it will exit.游戏 do-while 循环使游戏一直运行,直到用户猜出正确的数字,此时它将退出。 (This part I could not figure out). (这部分我想不通)。
  3. A numeric input validation do-while loop inside of the game loop, which makes sure the user's guess is valid.游戏循环内的数字输入验证 do-while 循环,可确保用户的猜测有效。
  4. A non-numeric input validation do-while loop which is after and outside of the game loop that asks the user if they want to play again, and checks for a valid 'Y' or 'N' response一个非数字输入验证 do-while 循环,它在游戏循环之后和之外,询问用户是否想再次玩,并检查有效的“Y”或“N”响应

Here is what I came up with:这是我想出的:

package week4;

//Imports
import java.lang.Math;
import java.util.Scanner;


public class Lab4d {
    public static void main(String[] args) {

        //Set up scanners
        Scanner again = new Scanner(System.in);
        Scanner num1 = new Scanner(System.in);

        //Set up variables
        int userInput = 0;
        int guesses = 0;
        int min = 1;
        int max = 100;
        int range = max - min + 1;
        int randNum = (int)(Math.random() * range) + min;
        boolean valid = false;

        //Outside loop
        do{
            //Describe the game
            System.out.println("\nThis program is a guessing game.");
            System.out.println("\nThe computer will pick a random number "
                               + "between 1 and 100.");
            System.out.println("\nYou will try to guess it.");
            System.out.println("\nLet's play!");

            //Insert Game loop here
            do {
                System.out.println("\nI'm thinking of a number " +
                                   "between 1 and 100.");
                //Insert valid guess checker here
                do {
                    System.out.println("Please enter your guess: ");
                    if (num1.hasNextInt()){
                        userInput = num1.nextInt();
                        valid = true;
                    }
                    else {
                        System.out.println("Error: Please enter a whole number.\n");
                        num1.nextLine();
                    }
                }while(!valid);

                if (userInput > randNum) {
                    System.out.println("\nToo high!");
                    guesses++;
                }
                else if (userInput < randNum) {
                    System.out.println("\nToo Low!");
                    guesses++;
                }
                else if (userInput == randNum) {
                    System.out.println("You got it!");
                    System.out.println("It took you" + guesses + "tries");
                    valid = true;
                }
            }while(!valid);


            //Insert play again checker
            do {
                System.out.println("\nDo you want to play again?");
                System.out.println("\nEnter 'Y' if yes and 'N' if no.");
                String play = again.nextLine();
                if (play.equalsIgnoreCase("Y")) {
                    valid = true;
                }
                else if (play.equalsIgnoreCase("N")) {
                    valid = true;
                }

                else {
                    System.out.println("Error: Please answer with 'Y' or 'N'");
                }
            }while(!valid);

        }while(!valid);
    }
}

I appreciate the help!我感谢您的帮助!

Your problem is in this part of the program你的问题在程序的这一部分

//Insert Game loop here
        do {
            System.out.println("\nI'm thinking of a number " +
                    "between 1 and 100.");
            //Insert valid guess checker here
            do {
                System.out.println("Please enter your guess: ");
                if (num1.hasNextInt()){
                    userInput = num1.nextInt();
                    valid = true; //>>>>> HERE YOU SET VALID TO TRUE 
                }
                else {
                    System.out.println("Error: Please enter a whole number.\n");
                    num1.nextLine();

                }

            }while(!valid);
            if (userInput > randNum) {
                System.out.println("\nToo high!");
                guesses++;
            }
            else if (userInput < randNum) {
                System.out.println("\nToo Low!");
                guesses++;
            }
            else if (userInput == randNum) {
                System.out.println("You got it!");
                System.out.println("It took you" + guesses + "tries");
                valid = true;
            }

        }while(!valid); //>>>>> AND THIS !VALID CHECK USES THE SAME "valid" boolean

So just use two separate booleans like so所以只需像这样使用两个单独的布尔值

//Imports
import java.util.Scanner;

public class Lab4d{
public static void main(String[] args) {

    // Set up scanners
    Scanner again = new Scanner(System.in);
    Scanner num1 = new Scanner(System.in);

    // Set up variables
    int userInput = 0;
    int guesses = 0;
    int min = 1;
    int max = 100;
    int range = max - min + 1;
    int randNum = (int) (Math.random() * range) + min;
    boolean valid = false;

    // Outside loop
    do {
        // Describe the game
        System.out.println("\nThis program is a guessing game.");
        System.out.println("\nThe computer will pick a random number " + "between 1 and 100.");
        System.out.println("\nYou will try to guess it.");
        System.out.println("\nLet's play!");

        // Insert Game loop here
        do {
            System.out.println("\nI'm thinking of a number " + "between 1 and 100.");
            // Insert valid guess checker here

            boolean userInputValid = false;
            do {
                System.out.println("Please enter your guess: ");
                if (num1.hasNextInt()) {
                    userInput = num1.nextInt();
                    userInputValid = true;
                } else {
                    System.out.println("Error: Please enter a whole number.\n");
                    num1.nextLine();
                }
            } while (!userInputValid);

            if (userInput > randNum) {
                System.out.println("\nToo high!");
                guesses++;
            } else if (userInput < randNum) {
                System.out.println("\nToo Low!");
                guesses++;
            } else if (userInput == randNum) {
                System.out.println("You got it!");
                System.out.println("It took you" + guesses + "tries");
                valid = true;
            }

        } while (!valid);

        // Insert play again checker
        do {
            System.out.println("\nDo you want to play again?");
            System.out.println("\nEnter 'Y' if yes and 'N' if no.");
            String play = again.nextLine();
            if (play.equalsIgnoreCase("Y")) {

                valid = true;
            }

            else if (play.equalsIgnoreCase("N")) {

                valid = true;
            }

            else {
                System.out.println("Error: Please answer with 'Y' or 'N'");
            }

        } while (!valid);

    } while (!valid);
}

} }

Just as an info (not directly related to your question), be careful comparing Integers with "==", it only works for values from -128 up to 127. (but you can use == for primitive type "int")正如信息(与您的问题没有直接关系),请小心将整数与“==”进行比较,它仅适用于 -128 到 127 的值。(但您可以将 == 用于原始类型“int”)

https://wiki.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching https://wiki.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

You don't need two Scanner objects.您不需要两个 Scanner 对象。 You can do the entire application with a single Scanner object:您可以使用单个 Scanner 对象完成整个应用程序:

Scanner input = new Scanner(System.in);

Your variables guesses , randNum , and valid should be initialized within the main game loop.您的变量猜测,randNum,有效应主游戏循环中被初始化 This way, when a new game starts, a new random value ( randNum ) is acquired, valid is reset to boolean false, and guesses is reset to 0 .这样,当一个新的游戏开始,一个新的随机值(randNum)获取,有效重置为布尔值false,并猜测被重置为0。

The valid = true; valid = true; located within the if (num1.hasNextInt()){ ... } IF code block of the Please enter your guess: prompt loop should be removed (deleted).位于if (num1.hasNextInt()){ ... } IF代码块中的Please enter your guess: prompt loop should be removed (deleted)。 This is to soon to say the input is valid and allows the prompt loop to exit.这很快就说明输入有效并允许提示循环退出。 This flag should only fall true if a correct value which matches the generated randNum value is supplied by the User.当用户提供与生成的randNum值匹配的正确值时,此标志才应为真。

Your IF statements for checking User input should be contained within the Please enter your guess: prompt loop.用于检查用户输入的IF语句应包含在Please enter your guess: prompt 循环中。 This allows the indicators Too High or Too Low to be displayed and the Please enter your guess: prompt to be re-displayed for another guess.这允许显示太高太低的指标,并且Please enter your guess:提示重新显示以进行另一次猜测。

The guesses variable is keeping an incorrect count (not enough).猜测变量保持不正确的计数(不够)。 You only need one guesses++;你只需要一个guesses++; and it should be placed directly after the User entry validity check IF/ELSE blocks.它应该直接放在用户输入有效性检查IF/ELSE块之后。

You should set valid to false before entering the Do you want to play again?您应该输入Do you want to play again?之前valid设置为false Do you want to play again? prompt loop.提示循环。

In your Do you want to play again?Do you want to play again? prompt loop you set valid to true if either Y or N is supplied.如果提供YN,则将有效设置为true 的提示循环。 So the main game loop is never passed through again.所以主游戏循环永远不会再通过。 Because you are using the valid boolean variable as a condition for all your loops you will want to ensure that if Y (yes) is supplied then valid meets the condition required to re-loop the main game loop (which happens to be boolean false) or use a different boolean flag for this main game loop (perhaps: boolean playAgain = false; ).因为您使用有效的布尔变量作为所有循环的条件,所以您需要确保如果提供Y (是),则有效满足重新循环主游戏循环所需的条件(恰好是布尔假)或者在这个主游戏循环中使用不同的布尔标志(也许: boolean playAgain = false; )。 Currently, if Y is supplied then valid should equal false and a break;目前,如果提供了Y ,则valid应该等于falsebreak; ought to be issued so as to exit the prompt loop.应该发出以退出提示循环。 Because valid is false the main game loop iterates again for a new game.因为valid是假的,所以主游戏循环会为新游戏再次迭代。 If N is supplied then simply exit the game at this point.如果提供了N ,那么此时只需退出游戏。 There is no need to just exit the prompt loop:无需退出提示循环:

 else if (play.equalsIgnoreCase("N")) {
    System.out.println("Thanks for playing...Bye Bye");
    System.exit(0);
 }

Placing the:放置:

System.out.println("\nI'm thinking of a number "
                 + "between 1 and 100.");

within a do/while loop is pointless.do/while循环中是没有意义的。 Keep the output to console but remove the do { and } while(!valid);将输出保留到控制台,但删除do {} while(!valid); . .

Alternative code might look something like:替代代码可能类似于:

Scanner input = new Scanner(System.in);

//Set up variables
int userInput = 0;
int guesses;
int min = 1;
int max = 100;
int range = max - min + 1;
int randNum;
boolean valid;
boolean playAgain = false;

//Outside loop
do {
    //Describe the game
    System.out.println("\nThis program is a guessing game.");
    System.out.println("\nThe computer will pick a random number "
            + "between 1 and 100.");
    System.out.println("\nYou will try to guess it.");
    System.out.println("\nLet's play!");

    randNum = (int) (Math.random() * range) + min;
    valid = false;
    guesses = 0;

    //Insert Game loop here
    System.out.println("\nI'm thinking of a number "
            + "between 1 and 100.");
    //Insert guess and validator here
    do {
        System.out.println("Please enter your guess: ");
        if (input.hasNextInt()) {
            userInput = input.nextInt();
        }
        else {
            System.out.println("Error: Please enter a whole number.\n");
            input.nextLine();
            continue;
        }
        guesses++;
        if (userInput > randNum) {
            System.out.println("\nToo high!");
        }
        else if (userInput < randNum) {
            System.out.println("\nToo Low!");
        }
        else if (userInput == randNum) {
            System.out.println("You got it!");
            System.out.println("It took you " + guesses + " tries");
            valid = true;
        }
    } while (!valid);

    //Insert play again checker
    valid = false;
    do {
        System.out.println("\nDo you want to play again?");
        System.out.println("\nEnter 'Y' if yes and 'N' if no.");
        String play = input.nextLine();
        if (play.equalsIgnoreCase("Y")) {
            playAgain = true;
            valid = playAgain;
        }
        else if (play.equalsIgnoreCase("N")) {
            playAgain = false;
            valid = true;
        }
        else {
            System.out.println("Error: Please answer with 'Y' or 'N'");
        }
    } while (!valid);
} while (playAgain);

System.out.println("Thanks for playing...Bye Bye");

To Do: Allow the User to Quit at any time.待办事项:允许用户随时退出。

This is a working code这是一个工作代码

Scanner scanner = new Scanner(System.in); //you only need one

int userInput = 0;
int guesses = 0;
int min = 1;
int max = 100;
int range = max - min + 1;
int randNum = (int)(Math.random() * range) + min;
boolean valid = false;
boolean playAgain = false;

do {
  System.out.println("\nThis program is a guessing game.");
  System.out.println("\nThe computer will pick a random number between 1 and 100.");
  System.out.println("\nYou will try to guess it.");
  System.out.println("\nLet's play!");

  do {
    System.out.println("\nI'm thinking of a number between 1 and 100.");
    do {
      System.out.println("Please enter your guess: ");
      if (scanner.hasNextInt()){
        userInput = scanner.nextInt();
        valid = true;
      }
      else {
        System.out.println("Error: Please enter a whole number.\n");
        scanner.nextLine();
        userInput = -1; //this is important
        valid = false;
      }
    } while(!valid);

    if (userInput == randNum) {
      System.out.println("You got it!");
      System.out.println("It took you " + guesses + " tries");
      valid = true;
    }
    else {
      valid = false; //this is important
      ++guesses;
      if (userInput > randNum) {
        System.out.println("\nToo high!");
      }
      else {
        System.out.println("\nToo Low!");
      }
    }
  } while(!valid);

  do {
    System.out.println("\nDo you want to play again?");
    System.out.println("\nEnter 'Y' if yes and 'N' if no.");
    String play = scanner.nextLine();

    if (play.equalsIgnoreCase("Y")) {
      valid = true;
      playAgain = true;
    }
    else if (play.equalsIgnoreCase("N")) {
      valid = true;
      playAgain= false;
    }
    else {
      valid = false;
      System.out.println("Error: Please answer with 'Y' or 'N'");
    }
  } while(!valid);
} while(playAgain);

scanner.close();

But, I suggest using more functions (especially for the inner for loops) to keep your code managable and more understandable.但是,我建议使用更多函数(特别是对于内部 for 循环)来保持您的代码可管理性和更易于理解。

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

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