我需要创建一个具有公共(public)方法 roll()
的类,它将返回 1 到 6 之间的随机整数。然后我需要创建一个测试程序来测量滚动的频率它可以计算 1000 卷中有多少个一、二、三等。
我的模具类如下:
import java.util.Random;
public class Die {
public int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
这是我的测试人员类(class):
public class DieTester extends Die {
public static void main(String[] args) {
int ones = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
for(int i = 0; i < 1000; i++) {
int roll();
if(n == 1) {
ones = ones + 1;
}
if(n == 2) {
twos = twos + 1;
}
if(n == 3) {
threes = threes + 1;
}
if(n == 4) {
fours = fours + 1;
}
if(n == 5) {
fives = fives + 1;
}
if(n == 6) {
sixes = sixes + 1;
}
}
System.out.println(ones);
System.out.println(twos);
System.out.println(threes);
System.out.println(fours);
System.out.println(fives);
System.out.println(sixes);
}
}
但是 Die Tester 类中的 int roll();
函数不起作用。我该如何解决这个问题?
最佳答案
您有两个问题:
int roll();
在当前位置不是有效语句- 如果您想保持
roll
的方式,您需要首先创建Die
的实例,否则将其设为静态
使用static
的解决方案
public class Die {
public static int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
public class DieTester {
public static void main(String[] args) {
// variables
for(int i = 0; i < 1000; i++) {
int n = Die.roll();
// your if logic
}
// printing
}
}
<小时/>
使用 Die
实例的解决方案
public class Die {
public int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
public class DieTester {
public static void main(String[] args) {
// variables
Die die = new Die();
for(int i = 0; i < 1000; i++) {
int n = die.roll();
// your if logic
}
// printing
}
}
<小时/>
在这两种情况下,使 DieTester
extend
Die
没有任何意义。
关于java - 创建测试程序来记录模具上滚动的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693916/