2013-09-25 166 views
-2

我被要求實現一個程序,該程序可以在一個jar中生成一個隨機數量的果凍豆,提示用戶猜測jar中有多少個果凍豆,並且計算用戶以前嘗試猜測的次數做對了。果凍豆猜測while循環?

這就是我的問題 - 讓程序計算用戶輸入猜測的次數。這裏是我的代碼:

import java.util.Scanner; 
import java.util.Random; 

public class JellyBeanGame 
{ 
public static void main(String[] args) 
{ 
    int numOfJellyBeans = 0;  //Number of jellybeans in jar 
    int guess = 0;      //The user's guess 



    Random generator = new Random(); 
    Scanner scan = new Scanner (System.in); 

    //randomly generate the number of jellybeans in jar 
    numOfJellyBeans = generator.nextInt(999)+1; 


    System.out.println("There are between 1 and 1000 jellybeans in the jar,"); 


do 
{ 
    System.out.print("Enter your guess: ");//prompt user to quess and read in 
    guess = scan.nextInt(); 

     if(guess < numOfJellyBeans) //if the quess is wrong display message 
     { 
      System.out.println("Too low."); 
     } 
     else if(guess > numOfJellyBeans); 
     { 
      System.out.println("Too High."); 
     } 
     else 
     { 
      System.out.println("You got it"); // display message saying guess is correct 
     } 
} while (guess != numOfJellyBeans); 





} 

}

+1

你只是想跟蹤的猜測數量?只需保留一個變量,並在scan.nextInt()返回時增加它。 –

+0

@gamernb是的,我可以給你一個例子嗎? –

+0

同意gamemb:添加一個像int guessCount = 0這樣的變量。在循環中,比如在猜測之後說,有一個guessCount ++。然後,您可以將您的顯示信息更改爲「您已獲得」+ guessCount +「猜測」。 – rajah9

回答

2

有你在while循環每次循環遞增計數器變量。事情是這樣的:

int num_guesses = 0; 
do { 
System.out.print("Enter your guess: ");//prompt user to quess and read in 
guess = scan.nextInt(); 
num_guesses++; // increment the number of guesses 

    if(guess < numOfJellyBeans) //if the quess is wrong display message 
    { 
     System.out.println("Too low."); 
    } 
    else if(guess > numOfJellyBeans) 
    { 
     System.out.println("Too High."); 
    } 
    else 
    { 
     System.out.println("You got it"); // display message saying guess is correct 
     System.out.println("It took you " + num_guesses + " guesses!"); // display message with number of guesses 
    } 
} while (guess != numOfJellyBeans); 
+0

你是說如果他們在第一次嘗試時得到它,你就會寫下「你花了0次猜測!」?只需在guess = scan.nextInt() –

+0

@gamernb後立即增加var,我不認爲有人會那麼幸運,但你是對的。 – fvrghl

+0

@fvrghl我想我現在明白了!感謝大家的幫助! –

0

do部分之前,定義一個變量int guessesCount = 0;然後就加一後各scanguessesCount++;

0

這是微不足道的:

int count = 0; 

// inside while loop 
     count++; 

// outside while loop 

// do what you want with count 
+0

因爲返回計數對於void函數是錯誤的。 – dognose

+0

即使你做了 - 你的答案有一個3歲的孩子可以給的質量。 +代表是重要的,對吧? – dognose

+0

肯定是傑夫。這不像他試圖解決P = NP。這是最簡單形式的正確答案。爲什麼複雜的事情? –