2015-12-06 65 views
-1

說明:編寫一個程序,使用蒙特卡羅採樣方法來估計 需要喝酒的電子桶的平均數量爲 獲獎。有一個五分之一的機會,一個瓶蓋將有獎品。與學校作業混淆

  1. 在Unit05 Assessments文件夾的 中創建一個名爲Monte Carlo Method的新項目。
  2. 在新創建的 項目文件夾中創建一個名爲BottleCapPrize的類。
  3. 確定每個人必須在 中打開多少個瓶蓋才能找到勝利上限。 (這代表一次試用。) 將此值打印到文本文件。關於使用骰子進行這種模擬,請回顧林博士的建議 。
  4. 提示用戶輸入試用次數。進行至少1000次試驗。
  5. 從輸出文件中讀回所有試驗的數據。
  6. 計算爲了贏得獎品而打開的平均上限數量。
  7. 將結果打印到屏幕上。

編輯:

import java.util.Scanner; 
import java.util.Random; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.io.File; 
public class BottleCapPrize 
{ 
    public static void main(String args[]) throws IOException 
    { 
     PrintWriter outFile = new PrintWriter(new File("bottleCap.txt")); 
     Scanner input = new Scanner (System.in); 
     int counter = 0; 
     int winCounter = 0;  

     Random randNum = new Random(); 
     int randNumber = randNum.nextInt(5) + 1; 

     System.out.print("How many trails would you like to do?"); 
     int trials = input.nextInt(); 

     while(trials != 1) 
     {    
      //Random randNum = new Random(); 
      randNumber = randNum.nextInt(5) + 1; 

      while(randNumber != 1) 
      { 

       if(randNumber != 1) 
       {    
        //System.out.println("You don't win"); 
       } 
       else if(randNumber == 1) 
       { 
        winCounter++; 
        outFile.println(counter); 
        System.out.println("You win in " + counter + "    bottles"); 
        winCounter++; 
        //System.out.println("counter: " + counter + "\tWin counter: " + winCounter); 
       } 
       counter++; 
      } 
     } 
     outFile.close(); 
    } 
} 
+1

這就是偉大的引用的行while(trials != 1)時應該有所幫助。那麼對此有何混淆? – Jabir

+1

到目前爲止,你有什麼嘗試(除了要求我們爲你寫完整的作業)? - 請參閱http://stackoverflow.com/help/how-to-ask – Jonnus

+0

@Jabir我編輯了我的原始文章並添加了我已經編寫的代碼。 –

回答

0

(這個答案被轉換the comments under the question成爲一個正式的答案)

遇到一個永無止境的(無限)循環,因爲你使用的是結構

while(trials != 1) 

尚未設置trials1。如果你想讓循環執行10次,只能使用for循環和計數器(我注意到你已經有了一個計數器,你正在遞增每次迭代,但本身沒有被引用)。

使用以下結構的環取代上述

for (int counter = 0; counter < 10; counter++)