1. 程式人生 > >java面向物件方法計算兩點之間的距離

java面向物件方法計算兩點之間的距離

package com.qianfeng.trxt0731;

public class Demo07 {
    public static void main(String[] args) {
        // 求兩點之間的距離
        Spot spot = new Spot(2, 1);
        Spot spot2 = new Spot(1, 1);
        double m = Spot.getDis(spot, spot2);
        System.out.println(m);
        // 使用非靜態方法
        double m1 = spot.getDis(spot2);
        System.out.println(m1);
    }
}

class Spot {
    double x;
    double y;

    public Spot() {
    }

    public Spot(double x, double y) {
        this.x = x;
        this.y = y;
    }

    // 靜態方法
    public static double getDis(Spot a, Spot b) {
        double c = 0;
        double i = Math.pow((a.x - b.x), 2);
        double j = Math.pow((a.y - b.y), 2);
        c = Math.sqrt(i + j);
        return c;
    }

    // 非靜態方法
    public double getDis(Spot a) {
        double c = 0;
        double i = Math.pow((a.x - this.x), 2);
        double j = Math.pow((a.y - this.y), 2);
        c = Math.sqrt(i + j);
        return c;
    }

}