有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

if语句如何在Java中创建运输成本计算器

我正在创建一个计算器来计算运费。代码是这样的:

class ShippingCalc {
    public static void main(String[] args) {
        int weight = 30;

        if (weight < 10) {
            System.out.println("Shipping costs $1.");
        }
        else if (weight < 20) {
            System.out.println("Shipping costs $2.");
        }
        else {
            System.out.println("Shipping costs $3.");
        }
    }
}

这是所有伟大的,但我想创建一个计算器,可以计算的基础上已经设定的值。例如,有这样一句话:

if (weight < 250) {
   // print("Shipping cost is $1);
} else if (weight < 499) {
   // print("Shipping cost is $2);
} else if (weight < 749) {
   // print...etc and it keeps going 

这将基于用户输入,这就是为什么我不希望已经有任何上述约束。有没有可能用Java制作这样一个计算器,不管重量有多大,它都会适当地计算运费并给出答案

如果是的话,我该怎么做


共 (2) 个答案

  1. # 1 楼答案

    首先,你需要一个计算运费的公式或表格。例如,“运费是每整十磅重量一美元”

    然后,你把重量加到公式中

    System.out.println("Shipping cost is $" + (int)(weight/10));
    

    如果你想让公式更复杂,你可以这样做:

    if (weight < threshold1) // price is first level
    // or, if you like, you can even do a calculation here
    else if (weight < threshold2) // price is second level
    

    其中,用户可以定义threshold1threshold2变量的值

    这些级别的数量可以是无限的:

    // "thresholds" is a sorted array of the weights at which prices change
    int[] thresholds = new int[num_thresholds];
    for (int checking = 0; checking < thresholds.length; checking++) {
        if (weight < thresholds[checking]) // price is prices[checking]
    }
    

    欢迎来到计算机编程的精彩世界

  2. # 2 楼答案

    如果成本权重遵循一个公式,你应该用它来计算成本(一点代数不会伤害任何人)

    如果权重到成本的分配是任意的,您可以使用权重作为键,成本作为值来创建NavigableMap

    然后可以使用^{}找到低于给定权重的最高权重

    范例

    public static Integer findCost(Integer weight, 
            NavigableMap<Integer, Integer> costMap){
        Map.Entry<Integer, Integer> cost;
        cost = costMap.lowerEntry(weight);
        if(cost == null){
            cost = costMap.firstEntry();
        }
        return cost.getValue();
    }
    

    使用映射的好处是,如果您使用^{}作为NavigableMap的实现,那么您的查找将平均为O(logn)