为什么我的构造函数不起作用?

时间:2014-03-17 16:50:01

标签: java class

我正在努力使用我的类构造函数来处理我正在使用的Java类。基本上,我们正在创建一个Trapezoid类,它接受三个双变量作为参数。这是我的类范围变量和构造函数的样子:

public class Trapezoid 
{

 double height;
 double longer;
 double shorter; 

public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
{
    heightofTrapezoid = height;
    longerSide = longer;
    shorterSide = shorter;
}

但是,当我尝试在我的驱动程序类中创建一个Trapezoid对象并打印出值时,它会为每个变量返回0。这是我的驱动程序类:

public class TrapezoidApp
{
    public static void main(String[] args)
    {
        // Arbitrary test values
        final double height = 10.0;
        final double longer = 5.5;
        final double shorter = 7.25;

        // Calculated offline from the above test values, used to verify code
        final double area = 63.75;

        // Instantiate a trapezoid object so that we can test it
        Trapezoid t = new Trapezoid(height, longer, shorter);
        double calculatedArea = t.getArea();

        // Our "test" is to display the received values next to the expected
        // values and verify that they match visually
        System.out.println("All of the following numbers should match:");
        System.out.println();
        System.out.println("       Expected  Received");
        System.out.println("       --------  --------");
        System.out.printf("Height:%8.2f  %8.2f\n", height, t.getHeight());
        System.out.printf("  Long:%8.2f  %8.2f\n", longer, t.getLongerSide());
        System.out.printf(" Short:%8.2f  %8.2f\n", shorter, t.getShorterSide());
        System.out.printf("  Area:%8.2f  %8.2f\n", area, t.getArea());
    }
}

我可以得到一些帮助吗?非常感谢。

3 个答案:

答案 0 :(得分:8)

作业从右到左。

heightofTrapezoid = height;

应该是

height = heightofTrapezoid;

其他领域相同。

答案 1 :(得分:1)

 double height;
 double longer;
 double shorter; 

public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
{
    height = heightofTrapezoid;
    longer = longerSide;
    shorter = shorterSide;
}

答案 2 :(得分:0)

如上所述,问题在于分配,我建议您学习在构造函数中使用 this 关键字。

 public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
  {
     this.height = heightofTrapezoid;
     this.longer = longerSide;
     this.shorter = shorterSide;
  }