2013-04-23 57 views
0

我遇到的問題是非常基本的,但是這是我沒有很好地掌握的東西。下面的程序使用遞歸來計算給定數量的骰子(由用戶輸入)總計爲用戶選擇的數字的概率。Diceroll概率方法結構

據我所知,方法DiceRoll是Diceroll類的一部分。但是,當我嘗試調用該方法時,出現錯誤。我相信這個計劃的結構有一些根本性的錯誤。有人可以幫我嗎?

import java.util.Scanner; 

public class DiceRoll { 

    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     double dice = 0; 
     int r = 0; 
     System.out.println("Please input the number of dice you wish to roll between 0 and 25: "); 
     if (in.nextInt() < 0 || in.nextInt() > 25){ 
      System.out.println("invalid number of dice"); 
     } else { 
      dice = in.nextInt();    
     } 
     System.out.println("What number between 0 and 125 do you wish to roll?"); 
     if (in.nextInt() < 0 || in.nextInt() > 125) { 
      System.out.println("invalid number, please choose between 0 and 125"); 
     } else { 
      r = in.nextInt(); 
     } 
    } 

    double DiceRoll(double dice,int r) { 
     if (dice==1 && (r<1 || r>6)){ 
      return 0; 
     } 
     if (dice==1 && (r>=1 && r<=6)){ 
      return (1.0/6); 
     } else { 
      return ((1.0/6)*DiceRoll(dice-1,r-1)); 
     } 
    } 
} 

DiceRoll(dice, r) 
+0

您至少可以嘗試格式化您的問題。 – 2013-04-23 22:49:48

+0

我的道歉,獵人。我會嘗試編輯它。 – purpscurp 2013-04-23 22:50:57

+0

@MrD對不起,我已經編輯過這個問題。 – 2013-04-23 22:54:26

回答

0

從主方法^ _ ^內部取出Diceroll方法
編輯: 實現DiceRoll方法不是主要的方法內聲明,但在調用它被放置的主要方法之外,內部移動它它應該可以工作

+0

DiceRoll不在他們的主要方法中。 – 2013-04-23 22:50:43

2

Java中的所有代碼都需要包含在方法或類中。你不能只是打電話給DiceRoll漂浮在你的班級中間。

你真正想要做的是從用戶那裏獲取你的輸入,然後在方法調用DiceRollmain裏面輸入。

+0

你能幫我分解這個程序的確切結構嗎?據我所知,DiceRoll類包含了包含掃描器和方法的主要方法DiceRoll,它依賴於變量dice和r。從Neil的評論中,我將DiceRoll方法轉移到主要方法中。你是說我可以在主方法中調用DiceRoll方法,它應該可以工作嗎? – purpscurp 2013-04-23 23:05:58

+0

沒關係,我已經想出了大部分。我將DiceRoll方法放在主方法外(但仍在類中),並在主方法中調用方法。謝謝!現在我需要在遞歸部分工作,但這似乎並不困難。 – purpscurp 2013-04-23 23:36:02

0

您需要刪除行

DiceRoll(dice, r) 

此外,而不是使用

double DiceRoll(double dice,int r) 

這需要您實例化一個對象,使用

static double RollDice(double dice, int r) 

爲靜態方法,您不必實例化該類型的對象以使其工作。我也將它重命名,以便編譯器不會抱怨它看起來像一個無效的構造函數方法。使用靜態方法,您只需在main方法的末尾撥打

RollDice(dice, r) 

你的代碼還有另一個問題 - 輸入不會像你想要的那樣行爲。我假設你想要檢查輸入是否有效,然後再詢問是否不合適。目前,它會說它是無效的,然後什麼也不做,但是當它有效時,它會立即期待另一個數字。改變你的語句是這樣的:

System.out.println("Please input the number of dice you wish to roll between 0 and 25: "); 
dice = in.nextInt(); 
while (dice < 0 || dice > 25){ 
    System.out.println("invalid number of dice"); 
    dice = in.nextInt();    
} 

,直到他們提供有效的輸入這隻會得到另一個號碼,如果他們進入一個無效的號碼,並且會循環。

+0

哦,我很確定,你的算法計算概率不會給出正確的答案。 – 2013-04-23 23:07:33