L.james L.james - 24 days ago 9
Java Question

I'm new to programming and not able to get this code

//Write a program that generates 100 random integers between 0 and 9 and then //reports the number of times each integer value was generated using an array of //ten integers to store the counts for the number of 0s, 1s,...9s.

//this is what I have so far

import java.util.Random;
public class Random {

public static void main(String []args){

int i = 0;
int randomInt = 0;
int[] counts = new int[10];
Random rand = new Random();

for (i = 1; i <= 100; ++i){
randomInt = rand.nextInt(9);
}

}

}

Answer

rand.nextInt(10) generates random numbers between 0 inclusive - 10 exclusive i.e from 0-9

To count the number of times the number generated, you need to get the position[it will be same as the index in this case] of the number in the array and increment it.

counts[rand.nextInt(10)]++;

Here is the code

public static void main(String[] args) {
    int i = 0;
    int[] counts = new int[10];
    Random rand = new Random();
    for (i = 0; i < 100; ++i) {
        counts[rand.nextInt(10)]++;
    }
    System.out.println(Arrays.toString(counts));
}

output

[13, 8, 8, 10, 14, 8, 11, 8, 10, 10]
Comments