計算兩點坐標距離與中點坐標


/*回顧一下數學公式:

兩點的坐標是(x1, y1)和(x2, y2)
則兩點之間的距離公式為 d=√[(x1-x2)²+(y1-y2)²]

注意特例:
當x1=x2時
兩點間距離為|y1-y2|
當y1=y2時
兩點間距離為|x1-x2|

中點坐標:midpoint(X,Y)

X=(X1+X2)/2

Y=(Y1+Y2)/2

*/

//自定義坐標類

public class Pointer {
private double x;
private double y;
public Pointer(double x,double y){//構造方法初始化
this.setX(x);
this.setY(y);
}
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 static double distance(Pointer a,Pointer b){//靜態方法,通過類名.方法名調用
double result= (Math.pow(a.getX()-b.getX(),2)+Math.pow(a.getY()-b.getY(),2));
return Math.sqrt(result);

}
public void display(){
System.out.println("("+this.getX()+","+this.getY()+")");
}
public String toString(){
return "("+x+","+y+")";

}
public boolean equals(Pointer obj){
if(this.getX()==obj.getX()&&this.getY()==obj.getY()){
return true;
}
return false;
}
//兩點坐標的中點
public static String minpoint(Pointer a,Pointer b){
double x=(a.getX()+b.getX())/2;
double y=(a.getY()+b.getY())/2;
return "("+x+","+y+")";


}

}

 

//測試類


public class Demotest {

public static void main(String[] args) {

Pointer [] test=new Pointer [2];//對象數組
test[0]=new Pointer(2, 2);
test[1]=new Pointer(3,3);
test[0].display();
test[1].display();
System.out.println("**********************開始**********************");
System.out.println(test[0].toString()+test[1].toString()+"兩點之間的距離:"+Pointer.distance(test[0], test[1]));
System.out.println(test[0].toString()+test[1].toString()+"兩點的中點坐標是:"+Pointer.minpoint(test[0], test[1]));
System.out.println(test[0].equals(test[1]));
}

}

/*******************當然也可選擇JDK里面的Pointer類****************/

import java.awt.Point;
import java.util.Scanner;

public class Test {
public static void main(String[] args){
System.out.println("請輸入有幾組:");
Scanner scanner = new Scanner(System.in);
int groupCount = scanner.nextInt();

double results[] = new double[groupCount];
for (int i=0;i<groupCount;i++) {
System.out.println("請輸入第"+(i+1) + "組2點的坐標(以,分隔):");
String line = scanner.next();
String[] values = line.split(",");
if (values.length != 4) {
System.out.println("輸入的數據格式不對!");
i = i--;
}
else {
double p1 = Double.valueOf(values[0]);//返回保持用參數字符串 s 表示的 double 值的 Double 對象
double p2 = Double.valueOf(values[1]);
double p3 = Double.valueOf(values[2]);
double p4 = Double.valueOf(values[3]);
results[i] = getDistance(p1, p2, p3, p4);
}
}

for (int i=0;i<results.length;i++)
System.out.println(results[i]);
}

public static double getDistance(double p1,double p2,double p3,double p4) {
double d = 0.0;
d = Point.distance(p1, p2, p3, p4);
return d;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM