gpt4 book ai didi

java - 为 Box 类创建测试驱动程序并测试其所有方法

转载 作者:行者123 更新时间:2023-11-30 05:25:53 25 4
gpt4 key购买 nike

public static void main(String[] args) {

double w;
double h;
double d;

Scanner input = new Scanner(System.in);

System.out.print ("Enter the width of your box:");
w= input.nextDouble();
System.out.print ("Enter the height of your box:");
h= input.nextDouble();
System.out.print ("Enter the depth of your box:");
d= input.nextDouble();

Box boxOne = new Box(w, h, d);
System.out.println(boxOne.toString());

boxOne.setDim(w, h, d);


}

}

class Box
{
private double width = 1.0;
private double height = 1.0;
private double depth = 1.0;

public Box (double w, double h, double d)
{
setWidth(w);
setHeight(h);
setDepth(d);
}

public void setWidth(double w)
{
if(w > 0)
{
width = w;
}
else
{
width = 1.0;
}
}

public void setHeight(double h)
{
if(h > 0)
{
height = h;
}
else
{
height = 1.0;
}
}

public void setDepth(double d)
{
if(d > 0)
{
depth = d;
}
else
{
depth = 1.0;
}
}

public void setDim(double width, double height, double depth)
{
double volume=width*height*depth;
System.out.println("The volume of the box is "+volume);
}

public double volume ()
{

}

public String getWidth()
{
return String.format("%f",width);
}
public String getHeight()
{
return String.format("%f",height);
}
public String getDepth()
{
return String.format("%f",depth);
}
public String toString()
{
return String.format("Width is %s.\nHeight is %s.\nDepth is %s.", getWidth(), getHeight(),getDepth());
}

public boolean equalTo (Box o)
{
}
}

我不明白如何在此代码中使用方法 public boolean equalTo (Box o)public double volume() 。我应该在这两个方法的主体中写什么?以及如何在main方法中使用它们?我不明白这两种方法。如何创建 boolean equalTo() 方法和 doublevolume() 方法,以及如何测试它们?

最佳答案

equalTo 方法需要比较两个对象的属性:

public boolean equalTo (Box o){
boolean widthEquals = o.width == this.width;

// other checks

return widthEquals && heightEquals && depthEquals;
}

体积方法对我来说看起来像简单的数学:

public double volume() {
return this.width * this.height * this.depth;
}

测试这些方法需要您设置一个测试框架,例如 JUnit,很多教程都介绍了该框架。例子有:

https://www.tutorialspoint.com/junit/junit_test_framework.htm

https://junit.org/junit4/faq.html#atests_1

测试音量方法将如下所示:

@Test
public void testVolume() {
Box box = new Box(1.0, 2.0, 3.0);

double expectedVolume = 1.0 * 2.0 * 3.0;

assertEquals(expectedVolume, box.volume());
}

关于java - 为 Box 类创建测试驱动程序并测试其所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640356/

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