为什么我的PairTester类的结果为零?

时间:2013-10-07 01:31:30

标签: java math

每次运行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());
    }
}

5 个答案:

答案 0 :(得分:3)

您在构造函数中的赋值是相反的,因此您的实例字段未按要求初始化。

更改此

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

为:

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

由于没有为val1val2实例字段分配值,因此这些字段将初始化为double默认值0.0d

答案 1 :(得分: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;
    }

...代替

答案 2 :(得分: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;
}

所以下次你不会混淆

答案 3 :(得分:0)

您必须将构造函数更改为此

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

答案 4 :(得分:0)

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