本文介绍了方法不能应用于给定的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的程序中,我试图在另一个类中调用throwDice
方法.
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));
}
}
当我编译它时,d.throwdice()
会弹出一个错误,提示无法应用.它说它需要一个int,没有参数.但是我在throwDice
方法中调用了一个int diceCount
,所以我不知道出了什么问题.
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;
}
}
此代码有两点错误:
- 它调用不带
int
的throwDice
(您已将其定义为public int throwDice(int diceCount)
,因此必须给它一个int
) - 每个循环调用
throwDice
两次
- It calls
throwDice
without anint
(you have defined it aspublic int throwDice(int diceCount)
, so you must give it anint
) - It calls
throwDice
twice each loop
您可以这样解决它:
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;
}
}
这篇关于方法不能应用于给定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!