Exercise 3 ———————————————————— RandomStats Create a RandomStats application tha
ID: 3632531 • Letter: E
Question
Exercise 3 ———————————————————— RandomStats
Create a RandomStats application that generates 500 random numbers between 0 and 9 and then displays (using arrays and randomnumgenerator)
the number of occurrences of each number. Application output should look similar to:
number occurences
1 43
2 41
3 54
4 52
5 47
6 46
7 53
8 46
9 49
note that the number of occurences are random hence do not need to match
import java.util.Random;
public class RanfomStats
{
public static void main(String[] args)
{
int []number =new int[10];
number[0]=0;
number[1]=1;
number[2]=2;
number[3]=3;
number[4]=4;
number[5]=5;
number[6]=6;
number[7]=7;
number[8]=8;
number[9]=9;
System.out.println("Numbers");
for (int i=0;i<number.length;i++)
{
System.out.println(number[i]);
}
Random numberofoccurences = new Random();
for (int i = 0; i < 500; i++) {
int roll = numberofoccurences.nextInt(9) + 1;
System.out.println(roll);
}
}
}
Explanation / Answer
public static void main(String[] args)
{
// 500 random numbers
int[] random = new int[500];
for(int i = 0; i < random.length; i++)
random[i] = (int)(Math.random()*10); // random number between 0 and 9
// count occurrences
int[] occurrences = new int[10];
for(int i = 0; i < random.length; i++)
occurrences[random[i]]++;
// print counts
for(int i = 0; i < 10; i++)
System.out.println(i+" "+occurrences[i]);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.