gpt4 book ai didi

java - 为什么我的构造函数不工作?

转载 作者:行者123 更新时间:2023-12-01 06:52:11 24 4
gpt4 key购买 nike

我正在为我正在使用的 Java 类的类构造函数而苦苦挣扎。本质上,我们正在创建一个梯形类,它接受三个 double 变量作为参数。这是我的类范围变量和构造函数的样子:

public class Trapezoid 
{

double height;
double longer;
double shorter;

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

但是,当我尝试在驱动程序类中创建梯形对象并打印出值时,它为每个变量返回 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());
}
}

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

最佳答案

从右到左赋值。

这个

heightofTrapezoid = height;

应该是

height = heightofTrapezoid;

其他字段也是如此。

关于java - 为什么我的构造函数不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com