非法论据例外 [英] Illegal Argument Exception

查看:285
本文介绍了非法论据例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个非常简单的点类,但是我收到一个错误,我无法确定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);

双倍距离= Math.sqrt(X + Y);
DecimalFormat df = new DecimalFormat(#。#####);

String pointsDistance =(+ distance);

pointsDistance = df.format(pointsDistance);

返回pointsDistance;
}

和测试代码

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

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

编辑



<我忘了添加我收到的错误:

 线程main中的异常java.lang.IllegalArgumentException:不能格式给定Object作为数字
在java.text.DecimalFormat.format(未知来源)
在java.text.Format.format(未知来源)
在Point.getDistance(Point.java) :41)PointTest.main的
(PointTest.java:35)


解决方案

你传递了一个 String ,但 格式方法需要 double 并返回字符串。更改

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

  String pointsDistance = df.format(distance); 


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)

解决方案

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

这篇关于非法论据例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆