/*回顾一下数学公式:
两点的坐标是(x1, y1)和(x2, y2)
则两点之间的距离公式为 d=√[(x1-x2)2+(y1-y2)2]
注意特例:
当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;
}
}