2

I tried to create an array of Random Numbers between 1 to 10 but I am getting a compilation Error. Can anyone tell me what's going wrong in my code?

import java.util.*;

public class Random {

    public static void main(String args[]){
        int arr[] = new int[1000];
        int num;
        Random rand = new Random();
        for (int i = 0; i <=arr.length; i++){
            num = 1+ rand.nextInt(10);
            arr[i] = num;
            System.out.println("Random No. Index: "+i+"\t Value : "+arr[i]);
        }
    }
}
MightyPork
  • 18,270
  • 10
  • 79
  • 133
Maverick
  • 39
  • 4

3 Answers3

3

You created a Random class which uses the existing java.util.Random class, which causes conflicts. Rename your class.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • It's kinda funny how often this exact same error appears on SO. Always with Random as a name of the test class xD – MightyPork Jan 03 '15 at 20:05
2

Your class is named Random and you are importing java.util.Random. I suspect that's the issue. So if you change the name of your class, this should work.

Also, your loop condition is not right. Change i <= arr.length; to i < arr.length or you will have a boundary issue (you'll write to arr[1000]).

Todd
  • 30,472
  • 11
  • 81
  • 89
1

You should name your class other than Random. Your name covers (makes invisible)
the Random class from the java.util package and you do need that class in your code.

For example, this code will compile and run fine.

import java.util.*;

class Random123 {

    public static void main(String args[]){
        int arr[] = new int[1000];
        int num;
        Random rand = new Random();
        for (int i = 0; i < arr.length; i++){
            num = 1 + rand.nextInt(10);
            arr[i] = num;
            System.out.println("Random No. Index: " + i + "\t Value : " + arr[i]);
        }
    }
}
peter.petrov
  • 38,363
  • 16
  • 94
  • 159