编程实现一个二维平面上点的类Point,包括下述内容:
(1)一个表示x坐标的double类型的数据域;
(2)一个表示y坐标的double类型的数据域;
(3)一个无参的构造方法;
(4)一个为x、y坐标设置初始值的有参的构造方法;
(3)一个返回当前点到原点距离的方法getDistanceToBase。
public class Point {
double x;
double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getDistanceToBase(){
return Math.sqrt(x*x + y*y);
}
}
答案如上
完整代码如下:
public static void main(String[] args) {
Point p2 = new Point();
Point p1 = new Point(3, 4);
System.out.println(String.format("p1距离原点的距离为%.2f", p1.getDistanceToBase()));
System.out.println(String.format("p2距离原点的距离为%.2f", p2.getDistanceToBase()));
}
public static class Point {
private double x;
private double y;
public Point() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] inputArr = input.split(" ");
x = Double.parseDouble(inputArr[0]);
y = Double.parseDouble(inputArr[1]);
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getDistanceToBase() {
return Math.sqrt(x*x + y*y);
}
}
运行结果如下:
-1 2
p1距离原点的距离为5.00
p2距离原点的距离为2.24