我将如何添加"你在...中猜对了!"

时间:2014-10-14 23:35:18

标签: 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

3 个答案:

答案 0 :(得分:1)

只需创建一些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");

答案 1 :(得分:0)

执行此操作的最简单方法是声明一个计数器整数,并在每次用户尝试时以逻辑递增。

int guessCounter = 0;

while(true) // Also do not use an infinite while loop, have an expression that can be terminated
{
...obtain input

if(guess < randomNum)
{
...
guessCounter++;

}
else if (guess > randomNum){
....
guessCounter++;
}

System.Out.println("The number of attempts " + guessCounter);
}

答案 2 :(得分:0)

您可以通过创建变量来存储尝试次数(例如int),然后在每次用户猜测时使用int添加一个变量来执行此操作:

variable++

如果你想要超越,你可以做到这一点,它说你在1 猜测 而不是说你如果用户在第一次尝试时获得正确的数字,则在1 猜测 中做到正确。我们可以通过使用三元Java运算符来实现这一点,这是一个非常紧凑的if语句:

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

      int tries = 0;

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


          //Rest of your code here
        }

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

  }

这正在做的是:String s = (tries == 1 ? "guess" : "guesses");

现在我们可以更改你正确的... 你的程序的一部分,如果用户说而不是猜猜在第一次尝试时猜测数字:

if this is true ? do this : else do this