Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't my program access the math methods in Java?

Tags:

java

math

class

I'm learning Java for the first time. I wrote a simple program:

public class Solver {
    public static void main(String[] args) {
        double angle = 1.5;
        double height = Math.sin(angle);
        System.out.print("The sine of " + angle + " is: ");
        System.out.println(height);
    }
}

When I attempt to compile this, I get the following error in the terminal:

Solver.java:4: cannot access Math
bad class file: ./Math.java
file does not contain class Math
Please remove or make sure it appears in the correct subdirectory of the classpath.
        double height = Math.sin(angle);
                    ^
1 error

Why can't I access the Math class?

like image 730
Raiden Worley Avatar asked May 22 '13 13:05

Raiden Worley


People also ask

Which package supports the mathematical methods in Java?

The java. lang. Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Is Java Math a default package?

Yes, Math is a standard Java class. Scanner is, too. You have to import it because it lives in the java. util package.

Do I have to import the Math class in Java?

Math class allows the use of many common mathematical functions that can be used while creating programs. Since it is in the java. lang package, the Math class does not need to be imported. However, in programs extensively utilizing these functions, a static import can be used.


2 Answers

If a file is called Math.java (which it seems to be), it must contain a class called Math. Take a look at this post. Java is looking for a file called ./Math.java, which doesn't contain seem to contain a class called Math in your case.

If you're actually trying to use the standard Java Math package, you need to either get rid of anything named Math.java in your project directory, since that will conflict with the built-in one, or else use a fully-qualified import to access the standard one: import java.lang.Math;. Imports from the java.lang package are not usually necessary, but if you have a conflicting name, it's important to use a fully-qualified import to access it explicitly.

Really, it's best to just get in the habit of putting everything in a named package and using fully-qualified imports all the time anyway. You'll save yourself a lot of hassle.

like image 116
Henry Keiter Avatar answered Nov 05 '22 14:11

Henry Keiter


Delete the file Math.java that you have probably inadvertently left in your source code directory. This file is preventing the normal usage of JDK's java.lang.Math class.

You should also note that defining classes in the default package is bad practice and will cause various issues for you along the way. Put your source code into a named package.

like image 21
Marko Topolnik Avatar answered Nov 05 '22 14:11

Marko Topolnik