我必须使用方法签名:public int roll((我只是不明白为什么我不能从我的新随机对象中调用该方法。请帮助。
import java.util.Random;
public class Die {
private int faceValue;
private Random random;
public Die() {
Random r = new Random();
r.roll(); // "The method roll() is undefined for the type Random
}
public int getFaceValue() {
return faceValue;
}
public int roll() {
for(int i = 1; i <= 11; i++)
{
faceValue = random.nextInt(6) + 1;
}
return faceValue;
}
}
您几乎没有基本错误,这是一个固定版本:
import java.util.Random;
public class Die {
private int faceValue;
private Random random;
public Die() {
this.random = new Random();
}
public int getFaceValue() {
return faceValue;
}
public int roll() {
for(int i = 1; i <= 11; i++){
faceValue = random.nextInt(6) + 1;
}
return faceValue;
}
}
,然后在您的main
方法中:
Die die = new Die();
System.out.println(die.roll());
&nbsp;
另外,您只能在构造函数中roll()
:
public Die() {
this.random = new Random();
System.out.println(this.roll());
}