4

我搜索了我的查询,但找不到任何有用的东西。我刚开始学习Java,我做了一个基本的猜谜游戏程序。我的问题是我需要计算用户所做的猜测次数,但我不确定如何执行此操作。我真的很感激你们能给我的任何帮助。到目前为止,这是我的代码:

double ran;
ran = Math.random();
int r = (int)(ran*100);

Scanner in = new Scanner (System.in);
int g = 0;

System.out.print("Please make a guess between 1 and 100: ");
g = in.nextInt();

while (g!=r){

  if (g<=0){
    System.out.print("Game over.");
    System.exit(0); 
  }

  else if (g>r){
    System.out.print("Too high. Please guess again: ");
    g = in.nextInt();
  }

  else if (g<r){
    System.out.print("Too low. Please guess again: ");
    g = in.nextInt();                               
  }
}

System.out.print("Correct!");
4

3 回答 3

3

您需要一个变量来跟踪您的猜测计数。在每场比赛只能运行一次的地方声明它,a la

int guessCount = 0

然后,在您的猜测循环中,递增guessCount.

guessCount++
于 2012-11-27T21:48:24.500 回答
2

有一个计数变量,并在每次迭代时在 while 内递增它。

    int count=0;
     while(g!=r) {

        count++;
        //rest of your logic goes here
        }
于 2012-11-27T21:48:34.123 回答
1

所以你会想要维护一个计数器,即一个变量,它将保持猜测次数的计数,并且每次你要求用户进行猜测时,你会希望将计数增加一。所以基本上,你应该在每次调用时递增计数器g = in.nextInt();

所以这就是你的代码应该做的事情......

double ran;
ran = Math.random();
int r = (int)(ran*100);
Scanner in = new Scanner (System.in);
int g = 0;
System.out.print("Please make a guess between 1 and 100: ");
int counter = 0;
g = in.nextInt();
counter++;
while (g!=r) {
    if (g<=0) {
        System.out.print("Game over.");
        System.exit(0);
    }
    else if (g>r) {
        System.out.print("Too high. Please guess again: ");
        g = in.nextInt();
        counter++;
    }
    else if (g<r) {
        System.out.print("Too low. Please guess again: ");
        g = in.nextInt();
        counter++;
    }
}
System.out.print("Correct!");
于 2012-11-27T21:57:21.333 回答