// // MyPoint.java // BodiesInASetting // // Created by Guy Lapalme on 20/05/05. // Copyright (c) 2005 Universite de Montreal. All rights reserved. // // similar to java.awt.Point but with a "non destructive" mode of operation // more compatible with the Smalltalk view class MyPoint { private int x,y; // CLASS part MyPoint(int x, int y){ this.x = x; this.y = y; } public int getX(){return x;} public int getY(){return y;} public static MyPoint parse(String s){ // return a MyPoint instance from a String as produced by toString() String[] ss = s.split("@"); if(ss.length!=2)return null; // badly formed Point try { return new MyPoint(Integer.parseInt(ss[0]),Integer.parseInt(ss[1])); } catch (NumberFormatException e){ return null; } } // method parse // INSTANCE part public String toString(){ return x+"@"+y; } MyPoint add(MyPoint p){ return new MyPoint(x+p.x,y+p.y); } MyPoint sub(MyPoint p){ return new MyPoint(x-p.x,y-p.y); } MyPoint scale(double f){ return new MyPoint((int)Math.round(f*x),(int)Math.round(f*y)); } double dist(MyPoint p){ return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)); } // MAIN for stand alone testing public static void main(String[] args){ MyPoint p0 = new MyPoint(50,50); MyPoint p1 = new MyPoint(100,100); MyPoint p2 = new MyPoint(200,75); MyPoint p3 = new MyPoint(p0.getX(),p0.getY()); System.out.println("p0 = "+p0+" vs p3 = "+p3); System.out.println(p1+" + "+p2+" = "+p1.add(p2)); System.out.println(p1+" - "+p2+" = "+p1.sub(p2)); System.out.println(p1+" * "+3+" = "+p1.scale(3)); System.out.println("dist("+p1+","+p2+") = "+p1.dist(p2)); System.out.println(MyPoint.parse("45@58")); System.out.println(MyPoint.parse("1@2@3")); System.out.println(MyPoint.parse("23.4@45")); } } // class MyPoint