2013-10-01 38 views
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 

每當內循環的同時,應該反覆打印輸入的值控制流。如何更改上面的代碼?

+0

你真的想它無限運行? –

+0

@RohitJain這會在一段時間後拋出OutOfMemoryException –

+0

@MarcoForberg它運行。請檢查它。跑步,等一會兒。 –

回答

1
int count = 0; 
while (true) 
{ 
    if (count > 2) 
    { 
     count = 0; 
    } 
    else 
    { 
     System.out.println("Value " + count); 
     count++; 
    } 
} 
+1

這也會打印'value3',這是錯誤的! – SudoRahul

+0

糾正了它!謝謝 –

+0

它的工作正常。謝謝 – Pinky

5

使用模量。

int count = 0; 

while(true) { 
    System.out.println("Value " + count); 
    count = ++count % 3;  
} 
+2

他的樣本輸出中沒有冒號,否則這是目前爲止最乾淨的答案。 – SplinterReality

+1

錯誤,第一次不會打印0。我測試了http://ideone.com/RQ11kg –

+1

你沒有測試,對吧? –

0

這可能是最短的變種

for(int count = 0; ; count = ++count % 3) { 
    System.out.println("Value " + count); 
} 
+0

'while(true)System.out.println(「Value」+(count ++)% 3);'更短;-) –

+0

@tobias_k true;)btw當count達到int的上限時拋出哪個異常?在一段時間內沒有用java工作 –

+2

@MarcoForberg。沒有。整數溢出永遠不會拋出Java中的異常。 –

0

試試這個,但請記住,在一定條件下,打破或將在無限循環去:

 int count = 0; 
     int max = 3; 
     while (true) 
     { 
      System.out.print("Value " + count); 
      count++; 
      count %= (max + 1); 
     }