如何防止输出降至零以下?

时间:2015-01-05 19:24:32

标签: java

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

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

}
}

1 个答案:

答案 0 :(得分:3)

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

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