繁体   English   中英

Java 做猜谜游戏

[英]Java do while Guessing Game

因此,对于上周我必须完成的一项作业,我必须使用 4 个 do-while 循环和 if 语句在 Java 中制作一个猜谜游戏。 我无法成功完成它,班级继续前进,没有提供任何帮助。 如果有人可以查看我的代码并告诉我我可以在哪里改进它以便程序正常运行,我将不胜感激。

为了简要描述赋值,赋值需要 4 个 do-while 循环:

  1. 主要的 do-while 循环,它包含大部分代码并保持程序运行直到用户想要退出
  2. 游戏 do-while 循环使游戏一直运行,直到用户猜出正确的数字,此时它将退出。 (这部分我想不通)。
  3. 游戏循环内的数字输入验证 do-while 循环,可确保用户的猜测有效。
  4. 一个非数字输入验证 do-while 循环,它在游戏循环之后和之外,询问用户是否想再次玩,并检查有效的“Y”或“N”响应

这是我想出的:

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);
    }
}

我感谢您的帮助!

你的问题在程序的这一部分

//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

所以只需像这样使用两个单独的布尔值

//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);
}

}

正如信息(与您的问题没有直接关系),请小心将整数与“==”进行比较,它仅适用于 -128 到 127 的值。(但您可以将 == 用于原始类型“int”)

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

您不需要两个 Scanner 对象。 您可以使用单个 Scanner 对象完成整个应用程序:

Scanner input = new Scanner(System.in);

您的变量猜测,randNum,有效应主游戏循环中被初始化 这样,当一个新的游戏开始,一个新的随机值(randNum)获取,有效重置为布尔值false,并猜测被重置为0。

valid = true; 位于if (num1.hasNextInt()){ ... } IF代码块中的Please enter your guess: prompt loop should be removed (deleted)。 这很快就说明输入有效并允许提示循环退出。 当用户提供与生成的randNum值匹配的正确值时,此标志才应为真。

用于检查用户输入的IF语句应包含在Please enter your guess: prompt 循环中。 这允许显示太高太低的指标,并且Please enter your guess:提示重新显示以进行另一次猜测。

猜测变量保持不正确的计数(不够)。 你只需要一个guesses++; 它应该直接放在用户输入有效性检查IF/ELSE块之后。

您应该输入Do you want to play again?之前valid设置为false Do you want to play again? 提示循环。

Do you want to play again? 如果提供YN,则将有效设置为true 的提示循环。 所以主游戏循环永远不会再通过。 因为您使用有效的布尔变量作为所有循环的条件,所以您需要确保如果提供Y (是),则有效满足重新循环主游戏循环所需的条件(恰好是布尔假)或者在这个主游戏循环中使用不同的布尔标志(也许: boolean playAgain = false; )。 目前,如果提供了Y ,则valid应该等于falsebreak; 应该发出以退出提示循环。 因为valid是假的,所以主游戏循环会为新游戏再次迭代。 如果提供了N ,那么此时只需退出游戏。 无需退出提示循环:

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

放置:

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

do/while循环中是没有意义的。 将输出保留到控制台,但删除do {} while(!valid); .

替代代码可能类似于:

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");

待办事项:允许用户随时退出。

这是一个工作代码

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();

但是,我建议使用更多函数(特别是对于内部 for 循环)来保持您的代码可管理性和更易于理解。

暂无
暂无

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

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