0
点赞
收藏
分享

微信扫一扫

Java运用构造方法,计算并输出两点间的距离

hoohack 2024-01-15 阅读 13

import java.util.Scanner;
public class javaTest {
    public static void main(String[] args) {
// TODO Auto-generated method stub
        double x1,y1,x2,y2;
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()) {
            x1=sc.nextDouble();
            y1=sc.nextDouble();
            x2=sc.nextDouble();
            y2=sc.nextDouble();
            Point p1=new Point(x1,y1);
            Point p2=new Point(x2,y2);
            double d=dist(p1, p2);
            System.out.printf("The distance is %.2f\n", d);
        }
        sc.close();
    }
    static double dist(Point p1,Point p2)
    {
        double s;
        double dx=Math.abs(p2.getX()-p1.getX()) ;
        double dy=Math.abs(p2.getY()-p1.getY());
        s=Math.sqrt(dx*dx+dy*dy);
        return s;
    }
}
class Point {
        public double x,y;
        public Point(double a,double b){
        x=a;
        y=b;
        }
public double getX(){
        return x;
        }
public void setX(double x){
        this.x=x;
        }
public double getY(){
        return y;
        }
public void setY(double y){
        this.y=y;
        }
}

----------------------------- 分割线 -------------------------------

public class Main {
    public static void main(String[] args) {
        Point p1,p2;
        p1=new Point(0,0);
        p2=new Point(3,4);
        System.out.println(p1.getPoint()+"和"+p2.getPoint()+"之间的距离是"+distance(p1,p2));
    }
    static double distance(Point p1, Point p2){
        return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
    }
}
class Point{
    double x,y;
    Point(double x,double y){
        this.x=x;
        this.y=y;
    }
    String getPoint(){
        return "("+x+","+y+")";
    }
}

举报

相关推荐

0 条评论