March 3, 2013

how to add random number to an array

Question by Lish

This is classwork. I’ve been reading and searching and everything is telling me to use the java.util.Random of which I understand how that works and wish I could use it. but my assignment specifically tells me to use the (int) (Math.random * number) of which I am having difficulty seeing where to apply into my array. everything I’ve seen has been the Random pulled from java.
It is the generate 100 random integers 0-9 and how many times they occur. If someone can assist?
My error is – Exception in “main” java.lang.array index out of bounds exemption:10 and obviously there is something in my code wrong too.

public class NumberOfTimes{

  public static void main(String[] args){

    int rand = (int)(Math.random() * 10);
    int[] counts = new int [10];

    for(int i = 0; i < 100; i++){

      counts[i]++;
    }//end for

    System.out.println("numbert" + "occurence ");

    for (int num = 0; num < counts.length; num++){

      System.out.println(num + "t" + counts[num]);
    }//end for

  }//end main

}//end NumberOfTimes   

Answer by Evgeniy Dorofeev

make this change

int[] counts = new int[100];
for (int i = 0; i < 100; i++) {
    counts[i] = (int) (Math.random() * 10);
}// end for

Answer by Starx

Your array can only hold 10 items, and on your loop you are accessing more than 10. Can be solved in two ways.

  • Either Increase your array length

    int[] counts = new int [100];
    
  • Or either decrease your count in for loop.

    for(int i = 0; i < 10; i++){
    

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!