Java实现每10名儿童免1名成人陪护费的规则需求
解决方案
你完全可以用整数除法简化逻辑,不用写一堆if判断。核心思路:
- 每10个儿童对应1个免费成人名额,用
childrenAmount / 10(Java整数除法会自动向下取整)就能算出最多可免的名额数 - 实际能减免的名额不能超过订单里的成人数量,所以用
Math.min()取两者的较小值
修改后的代码
import java.util.Scanner; public class TicketCalculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); final double ADULT_PRICE = 10.5; final double CHILD_PRICE = 7.3; final double CONCESSION_PRICE = 8.4; final double POSTAGE_PRICE = 2.34; // 获取用户输入 System.out.print("\nEnter the number of adults: "); int adultAmount = input.nextInt(); System.out.print("\nEnter the number of children: "); int childrenAmount = input.nextInt(); System.out.print("\nEnter the number of concessions: "); int concessionAmount = input.nextInt(); // 处理nextInt后的换行符,避免读取空字符串 input.nextLine(); System.out.print("\nPostage is £2.34 extra. Press Y accept, press N to decline: "); String postageChoice = input.nextLine(); // 计算可免费的成人数量 int freeAdults = Math.min(adultAmount, childrenAmount / 10); // 计算基础总价(减去免费成人的费用) double total = (adultAmount - freeAdults) * ADULT_PRICE + childrenAmount * CHILD_PRICE + concessionAmount * CONCESSION_PRICE; // 处理邮费 if (postageChoice.equalsIgnoreCase("Y")) { total += POSTAGE_PRICE; } // 格式化输出总价 System.out.printf("\nTotal cost: £%.2f", total); input.close(); } }
关键逻辑说明
- 免费名额计算:
childrenAmount / 10自动实现规则——19个儿童得1个名额,25个得2个,不足10则得0,完全匹配需求。 - 边界处理:
Math.min(adultAmount, childrenAmount / 10)避免出现"免费名额比实际成人多"的情况,比如成人只有1但儿童有20,最多也只能免1个。 - 输入修复:补上
input.nextLine()处理nextInt()遗留的换行符,避免邮费输入读取空值。
内容的提问来源于stack exchange,提问作者Hamza Khan
相关产品推荐
相关产品推荐

