在我的程序中,我試圖在另一個類中調用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
,所以我不知道什麼是錯的。
順便說一句,'throwDice'會拋出骰子'diceCount + 1'次,因爲'for'循環的條件是'j <= diceCount'。它會從'0'通過'diceCount'投擲'j'的骰子。 – rgettman