Exercise: Count Occurrences

Write a console program that
  1. asks the user how many random numbers to generate
  2. asks the user what the maximum value (inclusive) of each random number should be
  3. fills an array with the generated random numbers
  4. calculates how often each random number occurs in the array
Example program output (user input in green):
How many random numbers do you want to generate?
8
What is the maximum value (inclusive) of the random numbers?
5
Random numbers: 3, 5, 3, 5, 5, 0, 3, 2
Number 0 occurs 1 time
Number 1 occurs 0 times
Number 2 occurs 1 time
Number 3 occurs 3 times
Number 4 occurs 0 times
Number 5 occurs 3 times

Hints 💡

For counting the occurrences in an array, it's useful to create a second array. The index of the second array represents a number in the first array. The value at that index is the count for that number.

For example, if the first array consists of the numbers [1, 0, 1, 3, 0, 3], the second array would be [2, 2, 0, 2] because the number 0 occurs 2 times, the number 1 occurs 2 times, the number 2 occurs 0 times, and the number 3 occurs 2 times.

The length of this second array should be one more than the maximum value of the random numbers: If the maximum value is 3, the length of the second array should be 4 to count how often the numbers 0, 1, 2, and 3 occur in the first array.

First array
Value 1 0 1 3 0 3
Counting array
Value 2 2 0 2
Index 0 1 2 3

Hand in instructions

  1. Make sure your program runs correctly.
  2. Hand in your program by uploading Main.java to Moodle.