繁体   English   中英

如何在猜数游戏中添加猜数限制?

[英]How do I add a limit to the number of guesses in a number guessing game?

我不知道如何在我的猜数游戏中增加猜数限制。 我曾尝试在 while 语句之后添加一个 for 语句,但这使得代码只在第十次猜测时停止,并且从来没有赢家。 我删除了 while 语句,只执行了 for 语句,以确保用户每九次猜测都能得到正确的答案。 我的代码按照教授的要求分为两类。 我在下面都包括在内。 我会很感激我能得到的所有帮助。 谢谢!

GuessingGame.java:主类

public class GuessingGame {
    public static void main(String[] args) {
        new Guess().doGuess();
    }
}

猜猜.java

class Guess {
    private int answer = 0;
    int tries = 0;
    Scanner input = new Scanner(System.in);
    int guess, i;
    boolean win = false;
    int amount = 10;
    
    public Guess() {
        answer = generateRandomNumber();
    }

    //Generate a private number between 1 and a thousand
    private int generateRandomNumber() {
        Random rand = new Random();
        return rand.nextInt(1000) + 1;
    }

    public void doGuess() {
        while(!win) {
            System.out.println("You are limited to ten attempts."
                    + "Guess a number between 1 and 1000: ");
            guess = input.nextInt();
            if (guess > 1000 ) {
                System.out.println("Your guess is out of the range!");
            } else if (guess < 1) {
                System.out.println("Your guess is out of the range!");
            } else if (guess == answer) {
                win = true;
                tries++;
            } else if (guess < answer && i != amount -1) {
                System.out.println("Your guess is too low!");
                tries++;
            } else if (guess > answer && i != amount -1) {
                System.out.println("Your guess is too high!");
                tries++;
            }
        }
        System.out.println("Congragulations! You guessed the number!"
                + "The number was: " +answer);
        System.out.println("It took you " + tries + " tries");
    }
}

您可以在 while 循环中添加 if 语句。

 public void doGuess() {
           while(!win) {
            System.out.println("You are limited to ten attempts."
                    + "Guess a number between 1 and 1000: ");
            guess = input.nextInt();
            if(tries > 9) {
              ...whatever you want to happen when user has reached 10 guesses...
            }

暂无
暂无

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

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