gpt4 book ai didi

Java 对象和方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:20 26 4
gpt4 key购买 nike

我试图了解对象如何在 Java 上与自动变速箱车辆程序一起工作。我有一种方法可以提高汽车的速度speedIncrease,另一种方法可以获取当前对象的速度currentSpeed。在我的测试用例中,我在名为 renaultTransmissionBox 对象上创建了初始速度为 25 的对象。 speedUp 方法将速度增加 2,因此新速度应为 27。似乎该对象在第一次调用后丢失了所有修改。这怎么可能?

测试:设置

  @Before
public void setUp(){
private TransmissionBox renault;
renault = new TransmissionBox(25,10,20,30,40,50);
}

测试:速度 = 27

  @Test
public void speedIncrease(){
assertEquals(27,renault.speedUp().currentSpeed());
}

测试:速度 = 25

  @Test
public void speedIncrease(){
renault.speedUp();
assertEquals(25,renault.currentSpeed());
}


**TransmissionBox class**

public class TransmissionBox {
private int speed;
private int gear;
private int threesholdOne;
private int threesholdTwo;
private int threesholdThree;
private int threesholdFour;
private int threesholdFive;



public TransmissionBox(int iniSpeed, int iniThresholdOne, int iniThresholdTwo, int iniThresholdThree, int iniThresholdFour, int iniThresholdFive){
this.speed = iniSpeed;
this.threesholdOne = iniThresholdOne;
this.threesholdTwo = iniThresholdTwo;
this.threesholdThree = iniThresholdThree;
this.threesholdFour = iniThresholdFour;
this.threesholdFive = iniThresholdFive;

if(speed == 0 && speed < threesholdOne){
this.gear = 1;
}

else if(speed > threesholdOne && speed < threesholdTwo){
this.gear = 2;
}

else if(speed > threesholdTwo && speed < threesholdThree){
this.gear = 3;
}

else if(speed > threesholdThree && speed < threesholdFour){
this.gear = 4;
}

else{
this.gear = 5;
}

}


public TransmissionBox speedUp(){
TransmissionBox fasterCar = new TransmissionBox(speed+2, threesholdOne, threesholdTwo, threesholdThree, threesholdFour, threesholdFive);
return fasterCar;
}

public TransmissionBox speedDown(){
TransmissionBox slowerCar = new TransmissionBox(speed-2, threesholdOne, threesholdTwo, threesholdThree, threesholdFour, threesholdFive);
return slowerCar;
}

public int currentSpeed(){
return this.speed;
}

public int currentGear(){
return this.gear;
}


public String toString(){
return "speed: " + this.speed + "\n gear: " + this.gear;
}
}

最佳答案

您在错误的测试中调用了 speedUp()

关于Java 对象和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044101/

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