2013-11-05 69 views
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) 
+1

幸運的是,您不必查明錯誤,因爲您的編譯器會爲您執行該操作......定義了「p1」,「p2」和「pointsDistance」的位置?什麼類型是'p1'和'p2'?我假設'pointsDistance'是一個'String'。什麼'getX()'和'getY()'返回任何對象類型'p1'和'p2'是什麼?哪一行是'Point.java,第41行'?哪個是'PointTest.java 35行'? – nhgrif

+0

pointsDistance = p1.getDistance(x1,x2,y1,y2); 是第35行 – user2954611

+0

pointsDistance = df.format(pointsDistance);是41行 – user2954611

回答

3

你通過了String,但the format method預計double和返回String。從變化

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

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

取代它,仍然拋出相同的錯誤.... – user2954611

+0

我已經運行你的'getDistance'方法,與我的變化,我不會再出現錯誤。 – rgettman

+0

從技術上來說,有一種'格式',它把'Object'作爲參數(從'Format'繼承)。因此運行時錯誤而不是編譯。 –

1

替換此:

String pointsDistance = (""+ distance); 

pointsDistance= df.format(pointsDistance); 

有:

String pointsDistance = df.format(distance); 

的問題是,你的電話號碼的格式不接受的字符串。

+0

取代它,仍然拋出相同的錯誤.... – user2954611

+0

@ user2954611 - 您是否將參數更改爲'df.format()'?傳遞'double'而不是'String'是很重要的。 –

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

使用

String pointsDistance = df.format(distance); 

作爲格式方法需要double而不是string