You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java运费计算双if独立语句实现及每200英里计费问题求助

问题解决方案

核心问题定位

  • 里程计费逻辑错误:你使用浮点除法distance / 200计算计费单位,不符合需求中「不满200英里按1个完整单位收费」的规则。以你测试的1001英里为例,1001/200=5.005,需要向上取整为6个计费单位,对应每单位3美元的话,6*3=18美元,和预期结果一致。
  • 重量分档逻辑错误:所有分支判断使用了逻辑或||,导致规则完全失效。比如weight <3 || weight <=6只要重量≤6就会命中,永远不会走到更高档位的分支。
  • 参数校验冗余:重量、距离的合法性校验各写了两次重复的if判断,逻辑冗余。

精简实现方案(符合两条if+一条独立计算语句要求)

你可以通过合并参数校验为2条if语句,再用1条计算语句完成运费计算,完整修改后的代码如下:

import java.util.Scanner;

public class ShipIt {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        double weight;
        int distance;

        // 页面提示
        System.out.print("\t\t******Welcome to ShipIt******\n");
        System.out.print("***We are a low-charge, secure shipping company for packages up to 30 pounds***");

        // 读取用户输入
        System.out.print("\n\nEnter the weight of the package (1.0 - 30.0 pounds): ");
        weight = kb.nextDouble();
        System.out.print("Enter the miles to the destination (1 - 2000 miles): ");
        distance = kb.nextInt();

        // 第一条if:校验重量合法性
        if (weight <= 0 || weight > 30) {
            System.out.println("\nSorry, you have entered invalid data - program terminated");
            System.exit(1);
        }
        // 第二条if:校验距离合法性
        if (distance < 1 || distance > 2000) {
            System.out.println("\nSorry, you have entered invalid data - program terminated");
            System.exit(1);
        }

        // 独立运费计算语句:向上取整计算计费单位 + 三元运算符匹配重量费率
        double totalCost = Math.ceil(distance / 200.0) * (weight <= 3 ? 1.0 : weight <= 6 ? 2.0 : weight <= 10 ? 3.0 : weight <= 20 ? 4.0 : 5.0);

        System.out.println("The cost to ship the package is: $" + totalCost);
        kb.close();
    }
}

代码说明

  1. Math.ceil(distance / 200.0):对里程除以200的结果向上取整,只要有余数就进1位,刚好匹配按完整200英里单位计费的规则。
  2. 嵌套三元运算符:按重量档位匹配对应费率,逻辑和你给出的收费规则完全一致。
  3. 参数校验合并为两条if语句,符合你的需求。

内容的提问来源于stack exchange,提问作者Ritchell B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:39:04