实现坐标求长度关键算法。输入两点坐标(X1,Y1),(X2,Y2),计算并输出两点间的距离。输入数据有多组,每组 占一行,由 4 个实数组成,分别表示 x1,y1,x2,y2,数据之间用空格隔开。
注意:结果保留两位小数。
public class Week2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//输入两组数字 ,每组数字用空格隔开
System.out.print("输入四个数字,用空格隔开:");
String strCount = input.nextLine();
String[] strMath = strCount.split("\\s+");//使用正则表达式判断空格符号进行分割
double intMath1 =ParseDouble(strMath[0]);//第一组第一个数x
double intMath2 = ParseDouble(strMath[1]);//第一组第二个数y
System.out.println("第一组坐标为:"+intMath1+","+intMath2);
//第二组数值获取
double douMathTwo1 =ParseDouble(strMath[2]);//第二组第一个数x
double douMathTwo2 = ParseDouble(strMath[3]);//第二组第二个数y
System.out.println("第二组坐标为:"+douMathTwo1+","+douMathTwo2);
//算法计算他们之间的距离
Double douSum = Math.sqrt((intMath1-douMathTwo1)*(intMath1-douMathTwo1)+(intMath2-douMathTwo2)*(intMath2-douMathTwo2));
//输出结果
//String str = String.format("%.2f",douSum);//结果保留两位小数
System.out.printf("它们的距离为:%.2f",douSum);//结果保留两位小数
}
//判断字符串是否是数字
public static int ParseInt(String str){
if(!str.matches("[0-9]{1,}")){
System.out.println("这不是一个数值");
return -1;
}
return Integer.valueOf(str);
}
//判断字符串是否是数字
public static Double ParseDouble(String str){
if(!str.matches("[0-9]{1,}")){
System.out.println("这不是一个数值");
return null;
}
return Double.valueOf(str);
}
}