-1

I want to generate 500 random numbers and display them next to their indexes. I want the numbers to be 1 though 10. But when I run my code it only generates 13 random numbers and the numbers are greater than 10. Please help.

public class RandomStats {

    public static void main(String[] args) {

        int [] stats = new int [501];
        int numRolls;
        int outcome;

        for (int i = 0; i <=500; i++ ){
            outcome = (int) ( 10 * Math.random() + 1)
                    + (int) ( 10 * Math.random () + 1);
            stats[outcome] += 1;
        }

        for ( int i = 2; i <=500; i++) {
            System.out.println(i + ": " + stats[i]);
        }

    }

}
Glenn
  • 8,932
  • 2
  • 41
  • 54
  • 3
    You use the generated random number as index. You should use i as index and save the number as value of the stats array. – Konrad May 16 '18 at 21:59
  • `new int [501];` should be `new int [500];` , `stats[outcome] += 1;` should be `stats[i] = outcome;` , `i <=500` should be `i < 500`, `int i = 2` should be `int i = 0`, then [you've got one problem left](https://stackoverflow.com/questions/20389890/generating-a-random-number-between-1-and-10-java) – Ousmane D. May 16 '18 at 22:01

1 Answers1

-1

While saving in the array, you are doing stats[outcome] += 1;, where your array is updated with same index again and again and thats the reason you only see ~13 values and rest as 0. I believe it should be stats[i] =outcome+ 1;

arun k
  • 60
  • 4