Point Class
Completed
Create a class Point with int x, y, a constructor, a method double distanceTo(Point other) and a toString() returning (x, y). Read two points and print both and their distance (2 decimals).
Input
Two lines: x y.
Output
Three lines.
Example
Input
0 0 3 4
Output
(0, 0) (3, 4) 5.00
Editor
Java
Hints
this.x refers to the field when a parameter has the same name.
println(obj) calls obj.toString().
Solution explanation
A class bundles data (fields) with behaviour (methods). Extra classes go in the same file without public.
Show solution
import java.util.Scanner;
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
double distanceTo(Point other) {
int dx = x - other.x, dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Point a = new Point(sc.nextInt(), sc.nextInt());
Point b = new Point(sc.nextInt(), sc.nextInt());
System.out.println(a);
System.out.println(b);
System.out.printf("%.2f%n", a.distanceTo(b));
}
}