多数组方法运用问题:用while循环实现Java订单预览功能
Java订单预览:关联数组并使用while循环实现
完整可运行代码示例
public class OrderPreview { // 静态商品名称数组 private static final String[] NAMES = {"苹果", "香蕉", "橙子"}; // 静态商品单价数组 private static final double[] NETPRICES = {5.99, 3.49, 4.99}; public static void previewOrder(int[][] order) { int i = 0; // while循环遍历所有订单条目 while (i < order.length) { // 提取当前订单的商品编号(1-based)和购买数量 int productId = order[i][0]; int quantity = order[i][1]; // 转换为0-based索引,匹配NAMES和NETPRICES的数组下标 int arrayIndex = productId - 1; // 校验索引合法性,防止数组越界 if (arrayIndex >= 0 && arrayIndex < NAMES.length) { String productName = NAMES[arrayIndex]; double unitPrice = NETPRICES[arrayIndex]; double totalPrice = unitPrice * quantity; // 格式化输出,保证各列对齐 System.out.printf("%-8s %.2f %d %.2f%n", productName, unitPrice, quantity, totalPrice); } else { System.out.printf("无效商品编号:%d,跳过该订单条目%n", productId); } i++; } } public static void main(String[] args) { // 测试用订单数据 int[][] testOrder = {{1, 2}, {3, 5}, {2, 3}}; previewOrder(testOrder); } }
核心逻辑说明
- 索引转换:Order数组中的商品编号是1-based,而Java数组默认是0-based,必须通过
productId - 1转换为对应NAMES和NETPRICES的下标,这是关联三个数组的关键。 - while循环控制:用索引
i从0开始,循环条件设为i < order.length,每次循环后i++,确保遍历所有订单条目。 - 合法性校验:增加索引范围检查,避免因无效商品编号触发数组越界异常。
- 格式化输出:使用
System.out.printf控制输出格式,让各列对齐,提升可读性。
常见错误排查
- 未将1-based商品编号转换为0-based索引,导致取错商品信息;
- 循环条件错误(比如写成
i <= order.length),引发数组越界; - 未正确提取Order子数组中的数量值,或者遗漏循环索引自增步骤。
内容的提问来源于stack exchange,提问作者Oddy36
相关产品推荐
相关产品推荐

