2014-01-19 36 views
0

我理解重載的概念,並且我想我已經在這個程序中成功地完成了它;它運行良好,但輸出不正確。教我如何在Java中重載方法的練習程序不斷輸出錯誤的答案

該程序應該從兩個點計算圓的面積,一個是半徑,另一個是圓外的隨機點。這兩點由用戶給出,每個點由兩個數字組成。所以點1是x1,x2,而點2是y1,y2。

我做了一個測試運行,輸入數字1,2,3和4,這應該給我一個答案3.1458 ....(pi)。但是,它給了我25.132741228718352。

任何幫助搞清楚是什麼給我這個奇怪的輸出將不勝感激。

這裏是代碼 import java.util.Scanner; 公共類AreaCircle {

static Scanner input = new Scanner(System.in); 

public static double getDistance(double x1, double y1, 
          double x2, double y2) { 

    double dx = x2 - x1; 
    double dy = y2 - y1; 

    double distanceSquared = dx * dx + dy * dy; 
    double radius = Math.sqrt(distanceSquared); 
    return radius; 
} 

public static double areaCircle (double radius){ 
double area = (double)Math.PI * (radius * radius); 
return area; 
} 

public static double areaCircle (double x1, double x2, 
            double y1, double y2) { 
    double radius = getDistance(x1, x2, y1, y2); 

    double area = areaCircle (radius); 

    return area; 

} 
public static void main(String[] args) { 
System.out.print("Please input two points, with the first being \n" 
     + "the middle of the circle and the other being \n" 
     + "a point on the outside of the circle. These two points will \n" 
     + "be used to find the area of your circle. \n\n" 
     + "Input the first point here: "); 
double x1 = input.nextDouble(); 
System.out.print("Input the second point here: "); 
double x2 = input.nextDouble(); 
System.out.print("Input the third point here: "); 
double y1 = input.nextDouble(); 
System.out.print("Input the fourth point here: "); 
double y2 = input.nextDouble(); 
double result = areaCircle(x1, x2, y1, y2); 
System.out.println("Your result is: " + result); 
} 

}

+1

不是過載當你有兩個名字相同但參數不同的方法時? – JLPjohn

+0

這是!.my錯誤。太困了! –

+0

我有兩個areaCircles ....哈哈,沒關係 – JLPjohn

回答

0

你實際計算之間的距離(1,2)和(3,4),因爲你已經在distance切換x2y1(比較一下與area函數 - 你會明白我的意思)。

和(1,2)之間的距離(3,4)SQRT 8,當你替換該代入公式,它給8 * pi的面積〜= 25。

相關問題