// // hw2pr2.java // name: // import java.util.Scanner; // input library /* * This class, named Point, is a data structure * representing 2d points :-) */ class Point { // the data members that make up Points private double x; private double y; // a zero-input constructor public Point( ) { // call the two-input constructor with 0.0 and 0.0! this(0.0,0.0); } // a constructor that creates Points from an // x-coordinate and a y-coordinate public Point( double xcoord, double ycoord ) { this.x = xcoord; // the constructor sets the values this.y = ycoord; // for the data members, x and y } // a method (function) that prints Points public String toString() // it's always named toString { String result = "(" + this.x + "," + this.y + ")"; return result; } // a method (function) that returns the Manhattan distance // between the calling Point (this) and the input Point (p) public double manhattan_distance(Point p) { double x_difference = Math.abs( this.x - p.x ); double y_difference = Math.abs( this.y - p.y ); return x_difference + y_difference; } // The "main" method (function) is where the program // always begins its execution. Other methods will be // called as needed. Here, we don't use the command-line // inputs, named "args" public static void main(String[] args) { System.out.println("Hello from Java!"); // hi! Scanner inputter = new Scanner( System.in ); // input setup System.out.print("Type an x-coordinate: "); double xcoord = inputter.nextDouble(); System.out.print("Type a y-coordinate: "); double ycoord = inputter.nextDouble(); // create an object, named p1, of type Point: Point p1 = new Point( xcoord, ycoord ); // do it all again for a second object (p2) of type Point System.out.print("Type another x-coordinate: "); xcoord = inputter.nextDouble(); System.out.print("Type another y-coordinate: "); ycoord = inputter.nextDouble(); // our second object, named p2, of type Point: Point p2 = new Point( xcoord, ycoord ); // now print both Points and their Manhattan distance System.out.println("Point p1 is " + p1.toString()); System.out.println("Point p2 is " + p2.toString()); double mdist = p1.manhattan_distance(p2); System.out.println("Their manhattan distance is " + mdist); // and conclude with an appropriate message... if ( mdist > 42.0 ) { System.out.println("Too far!"); } else if ( mdist < 42.0 ) { System.out.println("Too close!"); } else { System.out.println("Perfect!"); } } // end of the main method } // end of the Point class