Eyal
Eyal

Reputation: 1709

Math.random() in Java

I have 2 classes in the same project and I'm using Math.random() in both of them. In the first all works fine, but at the second it says that random() is undefined. "The method random() is undefined for the type Math"

Any solutions?

Upvotes: 2

Views: 8563

Answers (2)

nachokk
nachokk

Reputation: 14413

You have to call

java.lang.Math.random() cause your class name is also Math, so you have to specify package.

Example :

public class Math {

    public static void main(String args []){
        System.out.println("JDK MATH RANDOM " +java.lang.Math.random()); // refers to java.lang
        System.out.println("My Math random implementation "+Math.random()); // refers to this class method, actually Math is redundant in this scope
    }

   public static double random(){
     //some implementation
   }

}

Upvotes: 2

user207421
user207421

Reputation: 310840

If you have a class of your own called Math you have to disambiguate which one you're talking about at the point of use, e.g. Java.lang.Math.random(). The simpler option is to change the name of your class. It's bad practice to reuse names from the JDK, especially from the java.lang package.

Upvotes: 1

Related Questions