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

5 に答える 5

3

a を渡しましたStringformatメソッドは a を予期し、 adoubleを返しますString。から変更する

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

String pointsDistance = df.format(distance);
于 2013-11-05T01:08:18.747 に答える
1

これを置き換えます:

String pointsDistance = (""+ distance);

pointsDistance= df.format(pointsDistance);

と:

String pointsDistance = df.format(distance);

問題は、数値形式が文字列を受け入れないことです。

于 2013-11-05T01:08:25.627 に答える
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;
}
于 2013-11-05T01:10:05.993 に答える