gpt4 book ai didi

java - 如何防止我的输出降至零以下?

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

我正在尝试计算公寓价格之间的差异,但我不能让价格变为负数/低于零。我想打印这两个价格。截至目前,我的输出与测试代码是正确的,除了一个是负面的。如何防止我的输出降至零以下?

public class Apartment {

private int rooms;
private int squareMeters;
private int pricePerSquareMeter;


public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) {
this.rooms = rooms;
this.squareMeters = squareMeters;
this.pricePerSquareMeter = pricePerSquareMeter;

}

public boolean larger(Apartment otherApartment){

if(this.squareMeters > otherApartment.squareMeters){
return true;
}
return false;
}
public int price(){

return squareMeters * pricePerSquareMeter;
}

public int priceDifference(Apartment otherApartment){


return this.price() - otherApartment.price();

}

}

public class Main {

public static void main(String[] args) {
// write testcode here
Apartment studioManhattan = new Apartment(1, 16, 5500);
Apartment twoRoomsBrooklyn = new Apartment(2, 38, 4200);
Apartment fourAndKitchenBronx = new Apartment(3, 78, 2500);


System.out.println( studioManhattan.priceDifference(twoRoomsBrooklyn) ); // 71600
System.out.println( fourAndKitchenBronx.priceDifference(twoRoomsBrooklyn) ); // 35400

}
}

最佳答案

如果你想要绝对差异,使用 Math.abs :

public int priceDifference(Apartment otherApartment)
{
return Math.abs(this.price() - otherApartment.price());
}

关于java - 如何防止我的输出降至零以下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786396/

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