我正在编写一个非常简单的点类,但是出现了错误,我无法确定字符串/双精度浮点数问题发生在哪里,也不知道如何解决。
public String getDistance (double x1,double x2,double y1,double y2) {
double X= Math.pow((x2-x1),2);
double Y= Math.pow((y2-y1),2);
double distance = Math.sqrt(X + Y);
DecimalFormat df = new DecimalFormat("#.#####");
String pointsDistance = (""+ distance);
pointsDistance= df.format(pointsDistance);
return pointsDistance;
}
以及测试代码
double x1=p1.getX(),
x2=p2.getX(),
y1=p1.getY(),
y2=p2.getY();
pointsDistance= p1.getDistance(x1,x2,y1,y2);
编辑
我忘记加上我收到的错误信息:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.DecimalFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at Point.getDistance(Point.java:41)
at PointTest.main(PointTest.java:35)
p1
,p2
和pointsDistance
定义在哪里?p1
和p2
是什么类型?我假设pointsDistance
是一个String
。无论p1
和p2
是什么对象类型,getX()
和getY()
返回什么?哪一行是Point.java
的第41行?哪一行是PointTest.java
的第35行? - nhgrifDecimalFormat
类,并知道format
方法期望什么样的参数。毕竟,错误是“非法参数异常”,直接指向了这一行。 - nhgrif