简体   繁体   中英

method cannot be applied to given types

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM