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 が必要であり、引数はありません。diceCountしかし、メソッドでintを呼び出したthrowDiceので、何が問題なのかわかりません。

4

3 に答える 3

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

このコードには 2 つの問題があります。

  1. throwDiceなしで呼び出しintます( として定義したpublic int throwDice(int diceCount)ため、 を指定する必要がありますint
  2. throwDiceループごとに2回呼び出します

次のように修正できます。

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;
  }
}
于 2013-05-17T00:31:14.953 に答える
1

throwDice()パラメータとして int を渡す必要があります。

public int throwDice(int diceCount){..}

そして、あなたは引数を提供していません:

d.throwDice();

これを機能させるには、パラメーターとして int を渡す必要があります。

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

diceCountのメソッド宣言の変数は、引数としてthrowDice(int diceCount)が必要でありint、引数が変数に格納されることを示しているだけでdiceCount、実際にはプリミティブを提供していませんint

最後に、あなたも throwDice2 回呼び出しています。

于 2013-05-17T00:30:17.807 に答える
1

throwDiceのように取ると定義しました。int

public int throwDice(int diceCount)

しかし、あなたは引数なしでそれを呼び出していますが、それはうまくいきません:

d.throwDice();
于 2013-05-17T00:30:56.147 に答える