方法不能应用于给定的类型
在我的程序中,我试图在另一个类中调用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
什么问题。
for(int i = 0; i < 100000; i++){ d.throwDice(); if(d.throwDice() == diceScore){ scoreCount += 1; } }
这段代码有两个问题:
- 它调用
throwDice
而没有int
(你已经将它定义为public int throwDice(int diceCount)
,所以你必须给它一个int
) - 它在每个循环中调用
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; } }
您已将throwDice
定义为采用如下int
:
public int throwDice(int diceCount)
但你是在没有任何args的情况下调用它而不会工作:
d.throwDice();
throwDice()
确实要求你传递一个int作为参数:
public int throwDice(int diceCount){..}
你没有提出任何论据:
d.throwDice();
您需要传递一个int作为参数才能使其工作:
int n = 5; d.throwDice(n);
throwDice(int diceCount)
的方法声明中的变量diceCount
仅表示它需要一个int
作为参数,并且该参数将存储在变量diceCount
,它实际上并不提供实际的原始int
。
最后,您还要两次调用throwDice
。