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 random numbers in the range from 0 to the maximum value
  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 another array, the counting array. The index of the counting array represents a number in the first array. The value at that index is the count for that number.

Since the range of our random numbers starts at 0, the length of this counting array should be one more than the maximum value of the random numbers: If the maximum value is 3, the length of the counting array should be 4 to count how often the numbers 0, 1, 2, and 3 occur in the random numbers array.

For example, if the array of random numbers is [1, 3, 0, 1, 2, 3], the counting array should be [1, 2, 1, 2] because:

Random numbers array
Value 1 3 0 1 2 3
Counting array
Value 1 2 1 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.