Reputation: 59
I need to make a class that has a public method roll()
which will return a random int between 1 and 6. Then I need to make a tester program that measures the frequency of rolls meaning it counts up how many ones, twos, threes, etc. in 1000 rolls.
My die class is as below:
import java.util.Random;
public class Die {
public int roll() {
Random rand = new Random();
int n = rand.nextInt(6) + 1;
return n;
}
}
and this is my tester 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);
}
}
However the int roll();
function in the Die Tester class is not working. How can I fix this?
Upvotes: 1
Views: 300
Reputation: 5794
luk2302's answer is correct. I think is worth to mention that you can do this a lot easier with 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);
Sample output showing the frequency of each number:
{1=178, 2=158, 3=165, 4=154, 5=183, 6=162}
Upvotes: 0
Reputation: 57114
You have two issues:
int roll();
is not a valid statement in its current placeroll
the way it is you need to create an instance of Die
first, otherwise make it static
Solution using 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
}
}
Solution using an instance of 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
}
}
In both cases it does not make much sense to make DieTester
extend
Die
.
Upvotes: 2