java - Distance between two coordinates -


i trying distance between coordinates, , doesn't seem work reason. grateful if help!

output:

the distance point point b 0.0. distance point point b 0.0. distance point point b 0.0. distance point point b 0.0. distance p1 p2 4.242640687119285 distance p1 p3 12.727922061357855

package gc01;  public class point {     private final double x;     private final double y;     private double distance;      public point(){         x=0.0;         y=0.0;     }      public point(double x, double y) {          this.x=x;          this.y=y;     }      public double distanceto(point a, point b) {         double dx = a.x - b.x;         double dy = a.y - b.y;         distance = math.sqrt(dx*dx + dy*dy);         return distance;     }     public string tostring(){         return "the distance point point b " + distance +".";     }  public static void main(string[] args){     point p0 = new point();     point p1 = new point(0.0,0.0);     point p2 = new point(3.0,3.0);     point p3 = new point(9.0,9.0);     system.out.println(p0.tostring());     system.out.println(p1.tostring());     system.out.println(p2.tostring());     system.out.println(p3.tostring());     system.out.println("the distance p1 p2 "+p1.distanceto(p1,p2));     system.out.println("the distance p1 p3 "+p1.distanceto(p1,p3)); } } 

one thing see when run main, you're calling point.tostring() method 4 times after make points. when distance variable hasn't been set yet because distanceto method hasn't been called.

point p0 = new point(); point p1 = new point(0.0,0.0); point p2 = new point(3.0,3.0); point p3 = new point(9.0,9.0); system.out.println(p0.tostring()); system.out.println(p1.tostring()); system.out.println(p2.tostring()); system.out.println(p3.tostring()); 

when these point.tostring calls happen, distanceto method hasn't been called distance hasn't been set of points.

you numbers outputting on last 2 lines because call distanceto method.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -