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

Asked

Viewed 145 times

2

I’m studying the Java programming language and I 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());
    }
}

ArchLinux

2 answers

6


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

Random is already defined in this Compilation Unit

You gave Random’s name to your class, and the compiler is confusing it with the java.util.Random. Like you don’t have the method nextInt() defined in his class he 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.

2

Try As Follows:

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

In this way it is not necessary to import.

In fact he cares, he must accuse error !

This is because your class name is also Random.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.