Java:计算do/while循环的数量

发布于 2024-12-08 15:43:25 字数 556 浏览 0 评论 0原文

所以我制作了这个猜谜游戏,计算机随机选择 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

祁梦 2024-12-15 15:43:25

使用计数器变量:

int guessCount = 0;

do {
guessCount++;
...
} while (...)

在循环结束时,您可以打印猜测计数。

Use a counter variable:

int guessCount = 0;

do {
guessCount++;
...
} while (...)

At the end of the loop, you can print the guess count.

甚是思念 2024-12-15 15:43:25

您可以简单地添加一个 intguesses = 0; 变量,并在 do 块的顶部递增它。

You could simply add an int guesses = 0; variable, and increment it at the top of the do block.

月亮是我掰弯的 2024-12-15 15:43:25
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); 
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); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文