【问题标题】:Limited number of tries to a simple game?一个简单游戏的尝试次数有限?
【发布时间】:2016-01-20 22:46:05
【问题描述】:

我如何将一个简单游戏的尝试次数限制为 3 次?我认为您会使用布尔值。但不确定。

import java.util.Scanner;

public class guess {

    public static void main(String[] args) {
        int randomN = (int) (Math.random() * 10) + 1;

        Scanner input = new Scanner(System.in);
        int guess;
        System.out.println("Enter a number between 1 and 10.");
        System.out.println();

        do {
            System.out.print("Enter your guess: ");
            guess = input.nextInt();

            if (guess == randomN) {
                System.out.println("You won!");
            } else if (guess > randomN) {
                System.out.println("Too high");
            } else if (guess < randomN) {
                System.out.println("Too low");
            } 
        } while (guess != randomN);
    }
}

【问题讨论】:

  • 您需要一个计数器来记录已进行的尝试次数,您需要在循环的每次迭代中递增计数器,并且您需要在do-while 循环中添加一个额外的退出条件跨度>

标签: java boolean java.util.scanner


【解决方案1】:
int attempts = 0;
do{
   attempts++;
   ....
}while(guess != randomN && attempts < 3);

【讨论】:

    【解决方案2】:

    使用标志。初始化为0。如果猜测正确则重置为0。如果不增加1。每次猜测之前,检查标志是否> 2。如果没有让继续,如果是的话。

    【讨论】:

      【解决方案3】:

      您可以在猜测失败期间递增。我相信变量应该位于循环之外。然后剩下的就是添加一个部分,当猜测用完时通知用户失败。

      public static void main(String[]args) {
          int rNumber = (int)(Math.random() * 10) + 1;
          Scanner input = new Scanner(System.in);
          int guess;
          int tries = 0;
          int success = 0;
      
          System.out.println("Enter a number between 1 and 10.");
          System.out.println();
          do {
              System.out.println("Enter your guess: ");
              guess = input.nextInt();
              if(guess == rNumber) {
                  System.out.println("You guessed right! You win!");
                  success++;
              } else if (guess < rNumber) {
                  System.out.println("Too low");
                  tries++;
              } else if (guess > rNumber) {
                  System.out.println("Too high.");
                  tries++;
              }
          } while(tries != 3 && success != 1 || success != 1);
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-23
        • 2018-06-25
        • 2015-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        相关资源
        最近更新 更多