Search code examples
javasqrt

Method sqrt is undefined in eclipse?


I'm working on a class for a school assignment where we're trying to use interfaces/comparables, and a root class called shape is being used to define other shape classes such as rectangles, circles, trapezoids, ect. The problem I'm running into is the use of the Square root method and the Power method when trying to make the trapezoid class.

What I'm trying to do is to get the 3rd and 4th side of a trapezoid, and because these are all going to be regular trapezoids, I can take the variable side1 (The top side of the trapezoid), subtract that from side2 (The bottom side of the trapezoid), divide it by two s that each side has the bottom half of the right triangle I'm trying to create, and then do the Pythagorean theorem to get that pesky 3rd side.

The problem is that every time I'm trying to run the Square root (sqrt) or power (pow) method to preform this, eclipse is giving me an error saying that "The method sqrt(double) is undefined for the type Trapezoid" I have no clue what I'm missing in this, so any help would be appreciated.

The code I have is as follows:

import java.lang.Math;

public class Trapezoid implements Shape {
public double side1;
public double side2;
public double height;


public Trapezoid(double side1, double side2, double height){
        this.side1 = side1;
        this.side2 = side2;
        this.height = height;

    }
public double perimeter(){ //THIS IS THE METHOD CAUSING PROBLEMS!
    double tosser = sqrt((((side2 - side1) / 2 *(side2 - side1) / 2) + (height*height) ) );
    return (side1 + side2 + 2 * tosser );
}//end perimeter


public double area(){
    return (((side1 + side2) / 2) * height);
}//end area

public String toString(){
    return "The area of the trapezoid is" + area() + ".";
}//end toString

public int compareTo(Shape that){
    int larger = 0;
    if(this.area() > that.area())
        larger = 1;
    else if(this.area() < that.area())
        larger = -1;
    return larger;
}
}

Also, the class for shape is rather small as well, but I can't make any changes to it for this assignment:

public interface Shape {
public double area();
public double perimeter();
}

Solution

  • You need to statically import the method to use it as an unqualified method

    import static java.lang.Math.sqrt;
    

    or use

    double tosser = Math.sqrt(...); 
    

    (importing from java.lang is unnecessary since those classes are imported by default)