javapoint

An example of the use of the Point class?


I'm trying to use Point(double x, double y), getX(), getY() to create a point and return it with toString(). I can't find an example of how to do this anywhere.

public class Point {

    private final double x;
    private final double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }


    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }


    @Override
    public String toString() {
        return ("(" + x + "," + y + ")"); 
    }
}

Solution

  • You might want to do this instead:

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
    

    Then...

    System.out.println(new Point(5.0, 5.0).toString());
    

    I don't know why you're setting the this.x and this.y values to 1 in your constructor. You should be setting them to the provided values of x and y.

    You also don't need the outer set of parentheses in the toString() method. return "(" + x + "," + y + ")"; will work fine.