Java: Calculate Total Price for Items with Positive Prices
public void calculateTotalPriceForItems(List<Item> items) {
BigDecimal totalPrice = BigDecimal.ZERO;
for (Item item : items) {
if (isPricePositive(item)) {
totalPrice = totalPrice.add(item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
}
}
logger.info('Total price: ', totalPrice);
}
// This private helper method checks whether an item's price is positive.
// It returns true if the price is greater than zero, and false otherwise.
private boolean isPricePositive(Item item) {
return item.getPrice().compareTo(BigDecimal.ZERO) > 0;
}
This Java code snippet defines a method named calculateTotalPriceForItems that calculates the total price for a list of Item objects. It iterates through each item in the list and multiplies its price by its quantity. The result is then added to a running total, totalPrice. The method ensures that only items with positive prices are included in the calculation by using a helper method isPricePositive which checks if the item's price is greater than zero.
The isPricePositive helper method uses the compareTo method of the BigDecimal class to compare the item's price with zero. If the price is greater than zero, the method returns true, indicating that the item's price is positive. Otherwise, it returns false. The final total price is logged to the console using the logger.info method.
原文地址: https://www.cveoy.top/t/topic/mQl9 著作权归作者所有。请勿转载和采集!