0
votes

In my program, I'm trying to call the throwDice method in a different class.

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));
}
}

When I compile it, an error pops up for the d.throwdice() and says it can't be applied. It says it needs an int and there are no arguments. But I called an int diceCount in the throwDice method, so I don't know what's wrong.

3
Incidentally, throwDice throws the dice diceCount + 1 times because the for loop's condition is j <= diceCount. It will throw the dice for j from 0 through diceCount.rgettman

3 Answers

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

There are two things wrong with this code:

  1. It calls throwDice without an int (you have defined it as public int throwDice(int diceCount), so you must give it an int)
  2. It calls throwDice twice each loop

You could fix it like this:

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;
  }
}
1
votes

You've defined throwDice as taking an int as follows:

public int throwDice(int diceCount)

But you are calling it without any args which just won't work:

d.throwDice();
1
votes

throwDice() does require you to pass an int as the parameter:

public int throwDice(int diceCount){..}

And you are providing no arguments:

d.throwDice();

You need to pass an int as the parameter in order to make this work:

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

The variable diceCount on the method declaration of throwDice(int diceCount) only indicates it requires an int as an argument and that the argument will be stored in the variable diceCount, it doesn't actually provide the actual primitive int.

Finally, you are also calling throwDice twice.