Print the value of a Point to the terminal

3.6k views Asked by At

I created a class that can find the distance between two points and the value of the midpoint between them:

public class Point {

    private double x;
    private double y;

    public Point (double x, double y) {

        this.x = x;
        this.y = y;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public static void main (String[] args) {
        Point p1 = new Point(1,1);
        Point p2 = new Point(4,5);
        System.out.println("The distance between p1 and p2 is: " + distance(p1, p2));
        System.out.println("The midpoint of p1 and p2 is: " + findMidpoint(p1, p2));
    }

    public static double distance(Point p1, Point p2) {
         return Math.sqrt((p1.getX() - p2.getX()) *  (p1.getX() - p2.getX()) + 
                          (p1.getY() - p2.getY()) *  (p1.getY() - p2.getY()));
    }

    public static Point findMidpoint (Point p1, Point p2) {
        return new Point((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
    }
}

This code compiles fine but when I run it, it gives the output:

The distance between p1 and p2 is: 5.0
The midpoint of p1 and p2 is: Point@15db9742

It gives the same value for the midpoint regardless of the values of p1 and p2. I want to output the midpoint in the format "(x,y)".

Could somebody also explain why I was forced to make the distance and findMidpoint methods static?

3

There are 3 answers

3
William Morrison On BEST ANSWER

Why do I get the same output each time?

Because you're not overriding the toString method. The value you're seeing is java's implementation of toString. Every object has this behavior.

Put this method in your point class to override java's toString implementation.

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

This will give you output in the format (x, y) as you requested.

Why are midpoint and distance static?

The methods being static was a design decision. They could be written to be non-static, but it would make less sense as the methods don't change the state of either point object involved.

0
Tom On

Point@15db9742 is the "default" output behavior of Object#toString(). If you want to change that, then override this method:

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

That should print:

Point[x=100.0, y=100.0]

instead.

0
vy32 On

You need to create a toString() method:

public String toString() {
    return String.format("Point(%f,%f)",x,y);
}

Then you get:

java Point
The distance between p1 and p2 is: 5.0
The midpoint of p1 and p2 is: Point(2.500000,3.000000)