Jake Burch
Jake Burch

Reputation: 57

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 + ")"); 
    }
}

Upvotes: 3

Views: 79005

Answers (3)

Special_octo20
Special_octo20

Reputation: 46

Same could be done with just the data class in Kotlin, with like this:

data class Point(val x: Double, val y: Double)

You can access all the methods above without creating it. Something like this:

val point = Point(3.0,4.0)
val result = point.toString()

Upvotes: 0

Nico
Nico

Reputation: 93

I think you look for that:

public class Point {
private double x;
private double y;

public Point(double x, double y){
    this.x=x;
    this.y=y;
}public String toString(){
    return "("+ this.x+","+this.y+")";
}
public static void main(String[] args){
    Point point= new Point(3,2);
            System.out.println(point.tostring());
    }
}

to had getX() getY() just have to create them.

Upvotes: 3

William Gaul
William Gaul

Reputation: 3181

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.

Upvotes: 7

Related Questions