Java:计算do/while循环的数量
所以我制作了这个猜谜游戏,计算机随机选择 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);
So I've made this guessing game where you the computer randomly picks a number between 1-100 and the user have to guess the correct number. I've made that working, now I want to calculate how many times the loop has repeated itself if you may say, or well how many times the user has "guessed".
This is the current code:
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用计数器变量:
在循环结束时,您可以打印猜测计数。
Use a counter variable:
At the end of the loop, you can print the guess count.
您可以简单地添加一个
intguesses = 0;
变量,并在do
块的顶部递增它。You could simply add an
int guesses = 0;
variable, and increment it at the top of thedo
block.