假设你要通过两种不同的包裹运输大米。你可能会编写一个程序来比较成本,该程序提示用户输入每个包裹的重量和价格,然后显示具有更优惠的包裹。
package pack2;
import java.util.Scanner;
public class CostingComparation {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter weight and price for package 1: ");
double w1 = input.nextDouble(), p1 = input.nextDouble();
System.out.print("Enter weight and price for package 2: ");
double w2 = input.nextDouble(), p2 = input.nextDouble();
System.out.println(compare(w1, p1, w2, p2));
}
}
//比较成本
public static String compare(double w1, double p1, double w2, double p2) {
if(w1 < 0 || w2 < 0 || p1 < 0 || p2 < 0) //出现负数时抛出异常
throw new IllegalArgumentException("Error input: negative data");
double unitPrice1 = p1 / w1; //单价 = 价格 / 重量
double unitPrice2 = p2 / w2;
if(Math.abs(unitPrice1 - unitPrice2) < 0.00001) //价格相等时
return "Two packages have the same price";
else
return "Package "+(unitPrice1 > unitPrice2 ? 2 : 1)+" has a better price";
}
}