Illegal Argument Exception

旧时模样 提交于 2019-12-01 04:00:33

问题


I am working on a really simple point class but I am getting an error and I can't pinpoint where the String/double problem is happening or how to fix it.

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;
        }

and the test code

double x1=p1.getX(),
                       x2=p2.getX(), 
                       y1=p1.getY(),
                       y2=p2.getY(); 

           pointsDistance= p1.getDistance(x1,x2,y1,y2);

EDIT

I forgot to add the error I'm receiving:

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:


You passed a String, but the format method expects a double and returns a String. Change from

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

to

String pointsDistance = df.format(distance);



回答2:


Replace this:

String pointsDistance = (""+ distance);

pointsDistance= df.format(pointsDistance);

with:

String pointsDistance = df.format(distance);

The problem is that your number format doesn't accept a string.




回答3:


The problem is that the format method takes a numeric value, not a String. Try the following:

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;
}



回答4:


Use

String pointsDistance = df.format(distance);

as the format method expects a double and not a string.




回答5:


Check out here first:
http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#format(double,%20java.lang.StringBuffer,%20java.text.FieldPosition)
Does your use of format method same as that?



来源:https://stackoverflow.com/questions/19780237/illegal-argument-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!