【问题标题】:Count number of user inputs计算用户输入的数量
【发布时间】:2012-11-27 21:44:31
【问题描述】:
我搜索了我的查询,但找不到任何有用的东西。我刚开始学习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!");
【问题讨论】:
标签:
java
input
numbers
counting
【解决方案1】:
您需要一个变量来跟踪您的猜测计数。在每场比赛只运行一次的地方声明它,la
int guessCount = 0
然后,在你的猜测循环中,递增 guessCount。
guessCount++
【解决方案2】:
有一个计数变量,并在每次迭代时在 while 内递增。
int count=0;
while(g!=r) {
count++;
//rest of your logic goes here
}
【解决方案3】:
因此,您需要维护一个计数器,即一个用于记录猜测次数的变量,并且您希望在每次要求用户进行猜测时将计数增加 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!");