所以我做了一个猜谜游戏,你在计算机上随机选择一个介于1-100之间的数字,用户必须猜测正确的数字。我已经让它工作了,现在我想要计算循环重复了多少次,或者用户“猜测”了多少次。
这是当前的代码:
int random = 0;
int a;
random = ((int)(Math.random()*100+1));
System.out.println("Guess the number");
do
{
a = Keyboard.readInt();
if (a > random)
{
System.out.println("Less");
}
if (a == random)
{
System.out.println("Correct");
}
if (a < random)
{
System.out.println("More");
}
}
while (a != random);
发布于 2011-10-09 11:23:21
int random = 0,guessed=0;
int a;
random = ((int)(Math.random()*100+1));
System.out.println("Guess the number");
do
{
guessed++;
a = Keyboard.readInt();
if (a > random)
{
System.out.println("Less");
}
if (a == random)
{
System.out.println("Correct");
System.out.println("Guessed" +guessed +"times ";
}
if (a < random)
{
System.out.println("More");
}
}
while (a != random);
发布于 2011-10-09 11:05:44
使用计数器变量:
int guessCount = 0;
do {
guessCount++;
...
} while (...)
在循环结束时,您可以打印猜测计数。
发布于 2011-10-09 11:05:48
您可以简单地添加一个int guesses = 0;
变量,并在do
块的顶部递增它。
https://stackoverflow.com/questions/7703050
复制相似问题