2013-05-17 71 views
0

在我的程序中,我試圖在另一個類中調用throwDice方法。方法不能應用於給定類型

public class SimpleDice { 
    private int diceCount; 

    public SimpleDice(int the_diceCount){ 
    diceCount = the_diceCount; 
    } 

    public int tossDie(){ 
    return (1 + (int)(Math.random()*6)); 
    } 

    public int throwDice(int diceCount){ 
      int score = 0; 
      for(int j = 0; j <= diceCount; j++){ 
      score = (score + tossDie()); 
      } 
      return score; 
     } 
} 

import java.util.*; 

public class DiceTester { 
public static void main(String[] args){ 

    int diceCount; 
    int diceScore; 

    SimpleDice d = new SimpleDice(diceCount); 

    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter number of dice."); 
    diceCount = scan.nextInt(); 
    System.out.println("Enter target value."); 
    diceScore = scan.nextInt(); 

    int scoreCount = 0; 

    for(int i = 0; i < 100000; i++){ 
    d.throwDice(); 
     if(d.throwDice() == diceScore){ 
     scoreCount += 1; 
     } 
    } 
    System.out.println("Your result is: " + (scoreCount/100000)); 
} 
} 

當我編譯它,一個錯誤的d.throwdice()彈出並說,它不能適用。它說它需要一個int並且沒有參數。但我在throwDice方法中調用了int diceCount,所以我不知道什麼是錯的。

+0

順便說一句,'throwDice'會拋出骰子'diceCount + 1'次,因爲'for'循環的條件是'j <= diceCount'。它會從'0'通過'diceCount'投擲'j'的骰子。 – rgettman

回答

3
for(int i = 0; i < 100000; i++){ 
d.throwDice(); 
    if(d.throwDice() == diceScore){ 
    scoreCount += 1; 
    } 
} 

有此代碼有兩個錯誤:

  1. 它調用throwDice沒有int(你已經把它定義爲public int throwDice(int diceCount),所以你必須給它一個int
  2. 它調用throwDice每個循環兩次

您可以修復它是這樣的:

for(int i = 0; i < 100000; i++){ 
int diceResult = d.throwDice(diceCount); // call it with your "diceCount" 
              // variable 
    if(diceResult == diceScore){ // don't call "throwDice()" again here 
    scoreCount += 1; 
    } 
} 
+0

謝謝!有效。 – user2387191

+0

@ user2387191不客氣:) – Doorknob

1

throwDice()確實需要你傳遞一個int作爲參數:

public int throwDice(int diceCount){..} 

而你提供任何參數:

d.throwDice(); 

你需要傳遞一個int作爲參數,以使這項工作:

int n = 5; 
d.throwDice(n); 

該方法的變量diceCount聲明throwDice(int diceCount)僅表示它需要一個int作爲參數,並且該參數將存儲在變量diceCount中,但它實際上並不提供實際的基本原型int

最後,您還打電話給throwDice兩次。

1

您已經定義throwDice爲採取int如下:

public int throwDice(int diceCount) 

但你沒有它是不會工作的任何ARGS稱之爲:

d.throwDice(); 
相關問題