非法参数异常

5

我正在编写一个非常简单的点类,但是出现了错误,我无法确定字符串/双精度浮点数问题发生在哪里,也不知道如何解决。

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)

1
幸运的是,你不必精确定位错误,因为编译器会为你做这件事... p1p2pointsDistance定义在哪里?p1p2是什么类型?我假设pointsDistance是一个String。无论p1p2是什么对象类型,getX()getY()返回什么?哪一行是Point.java的第41行?哪一行是PointTest.java的第35行? - nhgrif
pointsDistance = p1.getDistance(x1, x2, y1, y2); 是第35行。 - user2954611
pointsDistance = df.format(pointsDistance); 是第41行。 - user2954611
因此,有两个发布的答案解释了这个答案,但对我来说问题并不明显(我不是Java大师),编译器给了我足够的信息,让我知道我应该研究一下DecimalFormat类,并知道format方法期望什么样的参数。毕竟,错误是“非法参数异常”,直接指向了这一行。 - nhgrif
5个回答

3
你传递了一个 String,但是format 方法期望一个 double 并返回一个 String。请修改代码。
String pointsDistance = (""+ distance);
pointsDistance= df.format(pointsDistance);

String pointsDistance = df.format(distance);

我已经运行了你的 getDistance 方法,并进行了我的更改,现在不再出错。 - rgettman
从技术上讲,存在一个接受Object参数的format(从Format继承),所以发生了运行时错误而不是编译错误。 - James Montagne
@user2954611 你是否将一个 double 类型的参数传递给了 format 方法? - rgettman

1
替换此内容:
String pointsDistance = (""+ distance);

pointsDistance= df.format(pointsDistance);

使用:

String pointsDistance = df.format(distance);

问题在于您的数字格式不接受字符串。

@user2954611 - 你改变了 df.format() 的参数吗?重要的是传递 double,而不是 String - Ted Hopp

1
问题在于format方法需要一个数值类型的值,而不是String。尝试以下操作:
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 = df.format(distance);
    return pointsDistance;
}

1
使用

标签。

String pointsDistance = df.format(distance);

由于格式方法需要一个 double 而不是一个 string


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接