Java 非法参数异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19780237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Illegal Argument Exception
提问by user2954611
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.
我正在研究一个非常简单的点类,但出现错误,我无法确定 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;
}
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)
回答by rgettman
You passed a String
, but the format
methodexpects a double
and returns a String
. Change from
您传递了 a String
,但该format
方法需要 adouble
并返回 a String
。更改自
String pointsDistance = (""+ distance);
pointsDistance= df.format(pointsDistance);
to
到
String pointsDistance = df.format(distance);
回答by Ted Hopp
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.
问题是您的数字格式不接受字符串。
回答by blacktide
The problem is that the formatmethod takes a numeric value, not a String
. Try the following:
问题在于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;
}
回答by Daniel Larsson
Use
用
String pointsDistance = df.format(distance);
as the format method expects a double
and not a string
.
因为 format 方法需要 adouble
而不是 a string
。
回答by Mustakimur Rahman
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?
首先在这里查看:
http: //docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#format(double,%
20java.lang.StringBuffer,% 20java.text.FieldPosition)您使用的格式方法与此相同吗?