Error compiling code with import java.util.Random; random.nextInt ()

2

I'm studying the Java programming language and found an obstacle, by some chance I can not compile this code

import java.util.Random;
public class Random {
    public static void main(String[] args){
        Random num = new Random();
        System.out.println(num.nextInt());
    }
}

    
asked by anonymous 18.07.2016 / 21:50

2 answers

6

The real problem you should notice in the first line of error:

  

Random is already defined in this compilation unit

You have given the name Random to your class, and the compiler is confusing with java.util.Random . Since you do not have the nextInt() method defined in your class it says that this method does not exist.

Change the name of your class to avoid conflicts that is to work Ok.

See an example working on Ideone .

    
18.07.2016 / 21:57
2

Try the following way:

public class Random {
    public static void main(String[] args){
       java.util.Random num = new java.util.Random();
        System.out.println(num.nextInt());
    }
}

This way you do not need import .

It really does matter, it should accuse error!

This is because the name of your class is also Random .

    
18.07.2016 / 21:58