创建测试程序以记录模具上的辊子频率?

时间:2018-02-08 20:07:26

标签: java dice

我需要创建一个具有公共方法roll()的类,它将在1到6之间返回一个随机int。然后我需要制作一个测试滚动频率的测试程序,这意味着它计算了多少1000卷中的一个,两个,三个等。

我的骰子课程如下:

import java.util.Random;

public class Die {

  public int roll() {
    Random rand = new Random();
    int n = rand.nextInt(6) + 1;
    return n;
  }
}

这是我的测试人员课程:

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();函数不起作用。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您有两个问题:

  • int roll();在当前位置不是有效声明
  • if 您想要保持roll首先创建Die实例所需的方式,否则请static

使用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
    }
}

在这两种情况下,{em} DieTester extend Die都没有 感觉。

答案 1 :(得分:0)

luk2302's answer是正确的。我认为值得一提的是,您可以使用Random::ints轻松完成此任务:

Map<Integer, Long> dieTest = new Random().ints(1000,1,7) // generate 1000 pseudorandom values from 1 to 6
        .boxed()                                         // box each int to Integer
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // group by each distinct value counting the number of its occurrence in the stream

System.out.println(dieTest);

示例输出显示每个数字的频率:

  

{1 = 178,2 = 158,3 = 165,4 = 154,5 = 183,6 = 162}