非法论证例外

时间:2013-11-05 01:02:51

标签: java class illegalargumentexception

我正在研究一个非常简单的点类,但是我收到一个错误,我无法确定String / double问题发生的位置或如何解决它。

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)

5 个答案:

答案 0 :(得分:3)

您传递了String,但the format method需要double并返回String。改变

String pointsDistance = (""+ distance);
pointsDistance= df.format(pointsDistance);

String pointsDistance = df.format(distance);

答案 1 :(得分:1)

替换它:

String pointsDistance = (""+ distance);

pointsDistance= df.format(pointsDistance);

使用:

String pointsDistance = df.format(distance);

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

答案 2 :(得分: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;
}

答案 3 :(得分:1)

使用

String pointsDistance = df.format(distance);

因为格式方法需要double而不是string

答案 4 :(得分:1)

相关问题