2015-10-25 174 views
0

我遇到了一個隨機錯誤或錯誤的問題。 每次取決於代碼,它只會執行true或false操作。 有沒有人有解決方案,使其實際上是隨機的?爲什麼總是這樣?

int times; 

for (left = 0; left < times; left++) { 
     boolean result = (Math.random() < 0.5); 
     if(result = true){ 
      System.out.println("Heads"); 
     } 
     else if(result = false){ 
      System.out.println("Tails"); 
     } 
     System.out.println(result); 

    } 
+1

您需要使用'如果(結果==真)',或者只是'if(result)'而不是。 'if(result = true)'使'result'爲true。 –

+0

你應該使用==運算符來進行比較。即'result == true' –

+0

你的兩個方法都可以工作!謝謝 – INeedHelp

回答

2
if(result = true) 

沒有做什麼,你認爲它。它實際上是分配trueresult然後使用它作爲if語句的條件。因此條件將總是爲真。

使用==代替或者,因爲它是已經一個布爾值,只需使用(適當地從方式重命名變量過於籠統result):

boolean FiftyPercentChance = (Math.random() < 0.5); 
if (FiftyPercentChance) ...