2011-10-09 111 views
1

所以我製作了這個猜謎遊戲,計算機隨機挑選1-100之間的數字,用戶必須猜出正確的數字。我已經完成了這個工作,現在我想計算循環有多少次重複自己,如果你可能說,或者多少次用戶「猜測」。Java:計算do/while循環的數量

這是當前的代碼:

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);    

回答

1
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); 
4

使用計數器變量:

int guessCount = 0; 

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

在循環結束時,你可以打印猜測計數。

2

您可以簡單地添加一個int guesses = 0;變量,並將其增加到do塊的頂部。