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?
The java. lang. Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
Yes, Math is a standard Java class. Scanner is, too. You have to import it because it lives in the java. util package.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With