2011-07-18 22 views
0

我正在爲Java類編寫一個簡單的craps模擬器,並且由於某種原因它正在正常運行時遇到問題。它應該跟蹤「點」的損失並以「點」獲勝,但由於某種原因,這些值每次都傾向於1或0。第一輪的損失和勝利似乎在起作用。想知道如果有一個新鮮眼睛的人可以找出我搞砸了。謝謝!Java循環錯誤 - 需要新鮮的眼睛

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

class CrapsSimulator { 

    public static void main(String[] args) { 

    // Set up values we will use 
    int lossfirstroll = 0; 
    int winfirstroll = 0; 
    int losswithpoint = 0; 
    int winwithpoint = 0; 

    boolean gameover = false; 
    int point = 0; 

    // Loop through a craps game 100 times 
    for (int i = 0; i < 100; i++) { 

     // First roll -- random number within 2-12 
     Random rand = new Random(); 
     int random = rand.nextInt(11) + 2; 

     // Win on first roll 
     if (random == 7 || random == 11) { 
      winfirstroll++; 
      gameover = true; 
     } // Loss on first roll 
     else if (random == 2 || random == 3 || random == 12) { 
      lossfirstroll++; 
      gameover = true; 
     } else // Player has "point" 
     { 
      point = random; 
     } 

     // Check to make sure the game hasn't ended already 
     while (gameover == false) { 
      // Reroll the dice 
      random = rand.nextInt(11) + 2; 

      // Check to see if player has won 
      if (random == point) { 
       winwithpoint++; 
       gameover = true; 
      } 

      // Or if the player has lost 
      if (random == 7) { 
       losswithpoint++; 
       gameover = true; 
      } 

      // Otherwise, keep playing 
      gameover = false; 
     } 
    } 

    // Output the final statistics 
    System.out.println("Final Statistics\n"); 
    System.out.println("Games played: 100\n"); 
    System.out.println("Wins on first roll: " + winfirstroll + "\n"); 
    System.out.println("Losses on first roll: " + lossfirstroll + "\n"); 
    System.out.println("Wins with point: " + winwithpoint + "\n"); 
    System.out.println("Losses with point: " + losswithpoint + "\n"); 
    } 
} 
+0

我會將'new Random()'移到for循環的外面,以防隨機數字的熵被破壞。 – darvids0n

+0

@ darvids0n好的建議,但它沒有幫助。我欣賞它,但。 –

回答

2

或者通過調試器運行它,或者灑System.out.println並查看您的邏輯失敗的位置。這是功課嗎?

+0

OP說他正在編寫「Java類的程序」這個事實應該很簡單。 – darvids0n

+0

我也想說,使用調試器應該是第一件事。將一個斷點添加到「point = random」行應該使某些事情清楚。 –

+0

是的。這是作業。但它有什麼不同?我寫了所有的源代碼。它只是在某處尋找,我正在轉向你們「新鮮的眼睛」,看看我錯過的錯誤。 –

1

您的問題是gameover標誌。在內循環結束時,你總是將它設置爲false,這將使它永遠運行。

+0

對不起。這是我在調試時遇到的一個錯字。好眼雖然:) –

+0

錯字?對我來說,看起來像打開/關閉這個標誌是你的問題... – wjans

+0

我需要在for循環開始時將gameover設置爲false。謝謝。 –

相關問題