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]);
        }
    }
}
4
  • 1
    Do we guess which error you have? Commented Jan 3, 2015 at 20:03
  • possible duplicate of Fill an array with random numbers Commented Jan 3, 2015 at 20:06
  • num = 1+ rand.nextInt(10); /*the error exists in this line, it says nextInt() method does not exists for Random class, however the same works at other places*/ Commented Jan 3, 2015 at 20:06
  • Please edit your question to include that information. Commented Jan 3, 2015 at 20:07

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's kinda funny how often this exact same error appears on SO. Always with Random as a name of the test class xD
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]).

Comments

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]);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.