0

示例代码

int count=0;
while(true)
{ 
if(count>3)
System.out.print("value"+count);
count=count+1;
}

所需输出:

Value 0
Value 1
Value 2
Value 0
Value 1
Value 2

每当控制在 while 循环中流动时,它应该重复打印上述值。上面的代码怎么改?

4

4 回答 4

5

使用模数。

int count = 0;

while(true) {
   System.out.println("Value " + count); 
   count = ++count % 3;     
}
于 2013-10-01T09:35:37.583 回答
1
int count = 0;
while (true)
{
    if (count > 2)
    {
        count = 0;
    }
    else
    {
        System.out.println("Value " + count);
        count++;
    }
}
于 2013-10-01T09:37:07.623 回答
0

Try this but remember to break at some condition or it will go in infinite loop :

        int count = 0;
        int max = 3;
        while (true)
        {
            System.out.print("Value " + count);
            count++;
            count %= (max + 1);
        }
于 2013-10-01T09:42:00.420 回答
0

这可能是最短的变体

for(int count = 0; ; count = ++count % 3) {
    System.out.println("Value " + count);
}
于 2013-10-01T09:38:19.063 回答