一个运输公司使用下面的函数,根据运输重量(以磅为单位)来计算运输成本(以美元为单位)。
3.5, 若 0 < w <= 1
c(w) = 5.5, 若 1 < w <= 3
8.5, 若3 < w <= 10
10.5, 若 10 < w <= 20
编写程序,提示用户输入包裹重量,显示运输成本。如果重量大于 20,显示一条消息 “the package cannot be shipped”。
package pack2;
import java.util.Scanner;
public class Transportation {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter weight of the package: ");
System.out.println(cost(input.nextDouble()));
}
}
//运输成本
public static String cost(double weight) {
if(weight <= 0) //如果重量为负数,抛出异常
throw new IllegalArgumentException("Error Weight: "+weight);
if(0 < weight && weight <= 1) return "3.5";
else if(1 < weight && weight <= 3) return "5.5";
else if(3 < weight && weight <= 10) return "8.5";
else if(10 < weight && weight <= 20) return "10.5";
else return "the package cannot be shipped";
}
}