我搜索了我的查询,但无法找到任何有用的内容。我刚开始学习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!");
答案 0 :(得分:3)
您需要一个变量来跟踪您的猜测次数。声明它只会在每场比赛中运行一次,而不是
int guessCount = 0
然后,在猜测循环中,增加guessCount
。
guessCount++
答案 1 :(得分:2)
有一个count变量,并在每次迭代时在while内增加。
int count=0;
while(g!=r) {
count++;
//rest of your logic goes here
}
答案 2 :(得分: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!");