【问题标题】:Java: Calculate number of do/while loopJava:计算do/while循环的数量
【发布时间】:2011-10-09 11:02:06
【问题描述】:

所以我做了这个猜谜游戏,你的计算机随机选择一个介于 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);            

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    使用计数器变量:

    int guessCount = 0;
    
    do {
    guessCount++;
    ...
    } while (...)
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        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); 
        

        【讨论】:

          猜你喜欢
          • 2020-11-26
          • 1970-01-01
          • 2016-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-23
          • 2018-04-28
          相关资源
          最近更新 更多