用java代码
货运有分空运、陆运和海运三种。
空运:20千克内运费一律是100元,此后每多10千克就增长30元,50千克封顶(即重量大于50千克时一律按50千克的价格支付);
陆运:20千克内运费一律是50元,此后每多20千克就增长15元,100千克封顶(即重量大于100千克时一律按100千克的价格支付);
海运:20千克内运费一律是30元,此后每多20千克就增长5元,80千克封顶(即重量大于80千克时一律按80千克的价格支付);
请编写程序,要求:输入货运方式和货物重量,计算出所需的运费价格。要求程序中同时使用if和switch语句。
将问题转换为数学模型,然后转化为代码就行了
import java.util.Scanner;
public class Demo {
private static final String air = "air";
private static String land = "land";
private static String sea = "sea";
public static void main(String[] args) {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("你要选择的运货方式: 1、air(空运) 2、land(陆运) 3、sea(海运)");
int method = sc.nextInt();
System.out.println("请输入货物重量:");
int weight = sc.nextInt();
switch (method) {
case 1: //空运
System.out.println("所需的运费价格:" + totalPrice(air, weight));
break;
case 2: //陆运
System.out.println("所需的运费价格:" + totalPrice(land, weight));
break;
case 3: //海运
System.out.println("所需的运费价格:" + totalPrice(sea, weight));
break;
default:
System.out.println("输入的运货方式不存在,请重新输入:");
break;
}
}
}
public static double totalPrice(String method, int weight) {
if (method.equals(air)) {
if (weight > 50) {
return 190;
} else return weight <= 20 ? 100 : (weight - 20) / 10 * 30 + 100;
}
if (method.equals(land)) {
if (weight > 100) {
return 110;
} else return weight <= 20 ? 50 : (weight - 20) / 20 * 15 + 50;
}
if (method.equals(sea)) {
if (weight > 80) {
return 45;
} else return weight <= 20 ? 30 : (weight - 20) / 20 * +30;
}
return 0;
}
}