用java采用面向对象思想设计求两点间的距离,求代码
发布网友
发布时间:2022-05-12 16:59
我来回答
共1个回答
热心网友
时间:2023-10-14 19:51
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Point p1,p2;
System.out.println("请输入第1个点的x、y坐标:");
p1=new Point(sc.nextDouble(),sc.nextDouble());
System.out.println("请输入第2个点的x、y坐标:");
p2=new Point(sc.nextDouble(),sc.nextDouble());
System.out.println("点"+p1+"与点"+p2+"的距离是"+p1.distance(p2));
}
}
class Point
{
Point(double x,double y)
{
this.x=x;
this.y=y;
}
public String toString()
{
return "("+x+","+y+")";
}
double distance(Point p)
{
return Math.sqrt(Math.pow(this.x-p.x,2)+Math.pow(this.y-p.y,2));
}
private double x,y;
}