2013-10-07 67 views
1

每次運行我的PairTester類時,我都會爲每個結果保留零。誰能告訴我爲什麼?爲什麼我的PairTester類的結果爲零?

public class Pair { 
    private double val1; 
    private double val2; 

    public Pair(double aFirst, double aSecond) { 
     aFirst = val1; 
     aSecond = val2; 
    } 

    public double getSum() { 
     double sum = val1 + val2; 
     return sum; 
    } 

    public double getDifference() { 
     double difference = val1 - val2; 
     return difference; 
    } 

    public double getProduct() { 
     double product = val1 * val2; 
     return product; 
    } 

    public double getAverage() { 
     double average = (val1 + val2)/2; 
     return average; 
    } 

    public double getAbsolute() { 
     double absolute = Math.abs(val1 - val2); 
     return absolute; 
    } 

    public double getMinimum() { 
     double minimum = Math.min(val1, val2); 
     return minimum; 
    } 

    public double getMaximum() { 
     double maximum = Math.max(val1, val2); 
     return maximum; 
    } 
} 

這是我的測試類:

public class PairTester { 
    public static void main(String[] args) { 
     Pair myPair = new Pair(11, 15); 
     System.out.println("Sum = " + myPair.getSum()); 
     System.out.println("Difference = " + myPair.getDifference()); 
     System.out.println("Average = " + myPair.getAverage()); 
     System.out.println("Absolute = " + myPair.getAbsolute()); 
     System.out.println("Minimum = " + myPair.getMinimum()); 
     System.out.println("Maximum = " + myPair.getMaximum()); 
    } 
} 

回答

3

你在構造函數中分配反轉,並且由於它的實例字段都沒有得到初始化爲期望:

更改此

public Pair (double aFirst, double aSecond) 
{ 
    aFirst = val1; 
    aSecond = val2; 
} 

到:

public Pair (double aFirst, double aSecond) 
{ 
    val1 = aFirst; 
    val2 = aSecond; 
} 

由於沒有值被分配到val1val2實例字段,以便這些字段將被初始化是0.0ddouble默認值。

0

從你的代碼中,我們可以看到,你有實例字段初始化VAL1和val2值。任何實例字段的默認值爲零。這就是爲什麼你總是得到零作爲你的PairTester類的結果。

public Pair (double aFirst, double aSecond) 
{ 
    aFirst = val1; 
    aSecond = val2; 
} 

試圖改變(正確方法)

public Pair (double aFirst, double aSecond) 
{ 
    val1 = aFirst; 
    val2 = aSecond; 
} 

建議使用

public Pair (double val1, double val2) 
{ 
    this.val1 = val1; 
    this.val2 = val2; 
} 

所以下次你不會混淆

0

你必須改變構造這個

public Pair (double aFirst, double aSecond) 
{ 
    val1 = aFirst; 
    val2 = aSecond; 
} 
+0

太謝謝你了!而且我真的認爲我已經明白了......初學者的問題!哈哈! – user2840682

1

這是因爲你指定的實例字段您參數構造函數的

public class Pair 
{ 
    private double val1; 
    private double val2; 

    public Pair (double aFirst, double aSecond) 
    { 
     aFirst = val1; 
     aSecond = val2; 
    } 

val1val2將被初始化爲0自動

嘗試使用

public Pair (double aFirst, double aSecond) 
    { 
     val1 = aFirst; 
     val2 = aSecond; 
    } 

代替...

0

嘗試

public Pair (double aFirst, double aSecond) 
{ 
    val1 = aFirst; 
    val2 = aSecond; 
}