java - 我该如何添加 "You got it right in ... guesses!"

标签 java

我需要添加“你猜对了……猜对了!”但我不太确定怎么做。有人可以向我解释一下如何在java中做到这一点吗?

我希望它在最后显示一个 println ,说明用户尝试了多少次才能获得正确的数字。

import java.util.*;

public class prog210c
{
  public static void main()
  {
      Scanner sc = new Scanner(System.in);
      Random rn = new Random();

      int randomNum = rn.nextInt(90) + 10;

      System.out.println("I am thinking of a number between 1 and 100");

      while (true) {
          System.out.print("What do you think it is? ");
          int guess = sc.nextInt();

          if(guess < randomNum)
          {
              System.out.println("Higher--Try Again");
          }

          else if(guess > randomNum)
          {
              System.out.println("Lower--Try Again");
          }

          else if(guess == randomNum)
          {
              System.out.println("Correct!");
              break;
          }

          else
          {
              System.out.println("Enter a number between 1 and 100");
          }
        }

      //System.out.println("You got it right in " + + " guesses");

  } //end main
} //end class

最佳答案

只需创建一些 int 变量来存储您的尝试次数,并在每次读取猜测时递增它。

int attempts = 0;

System.out.println("I am thinking of a number between 1 and 100");

while (true) {
    System.out.print("What do you think it is? ");
    int guess = sc.nextInt();
    attempts++;

    /**
     * The rest of your loop code here.
     */
}

System.out.println("You got it right in " + attempts + " guesses");

关于java - 我该如何添加 "You got it right in ... guesses!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372139/

相关文章:

java - SWT 中的鼠标事件

java - 在 Intellij 中调试时,我可以在返回之前找出返回值吗?

java - ehcache hibernate 4

java - 为什么我们必须在 AES 算法中使用 Base64 库?

java - 创建用于创建文件的构造函数

java - 我们如何为树查看器创建子上下文菜单

java - 为什么 hasNext() 不会变成 false?

java - 服务器更新 tomcat 7 后抛出 Log4J 错误

java - 奇怪的Guice注入(inject)错误

java - 按后退按钮时强制关闭