运行结果为:
违禁物品:柴油重量为0.5.禁止携带!
违禁物品:硫酸重量为0.1.禁止携带!
违禁物品:硫磺 重量为0.2禁止携带!
非违禁品总重量为21.05超过20kg,超出部分请托运!
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入违禁物品 1 的名称:");
String item1 = scanner.nextLine();
System.out.print("请输入违禁物品 1 的重量:");
double weight1 = scanner.nextDouble();
String item2 = scanner.nextLine();
System.out.print("请输入违禁物品 2 的重量:");
double weight2 = scanner.nextDouble();
String item3 = scanner.nextLine();
System.out.print("请输入违禁物品 3 的重量:");
double weight3 = scanner.nextDouble();
System.out.println("非违禁品总重量为" + scanner.nextDouble() + ",超过 20kg,超出部分请托运!");
try {
double totalWeight = 0;
for (String item : items) {
totalWeight += scanner.nextDouble();
}
if (totalWeight > 2000) {
System.out.println("非违禁品总重量为" + totalWeight + ",超过 20kg,超出部分请托运!");
throw new Exception("超出部分请托运!");
} else {
System.out.println("非违禁品总重量为" + totalWeight + ",符合规定,欢迎携带行李!");
}
} catch (Exception e) {
System.out.println("违禁物品:柴油重量为 0.5.禁止携带!");
System.out.println("违禁物品:硫酸重量为 0.1.禁止携带!");
System.out.println("违禁物品:硫磺重量为 0.2 禁止携带!");
}
}
}
class OverweightException extends Exception {
public OverweightException(String message) {
super(message);
}
}
class ForbiddenItemException extends Exception {
public ForbiddenItemException(String message) {
super(message);
}
}
class Luggage {
private double totalWeight;
private int forbiddenItemCount;
public Luggage() {
totalWeight = 0.0;
forbiddenItemCount = 0;
}
public void addItem(String name, double weight) throws ForbiddenItemException {
if (name.equals("diesel") && weight > 0.0) {
throw new ForbiddenItemException("违禁物品:柴油重量为" + weight + "。禁止携带!");
} else if (name.equals("sulfuric acid") && weight > 0.0) {
throw new ForbiddenItemException("违禁物品:硫酸重量为" + weight + "。禁止携带!");
} else if (name.equals("sulfur") && weight > 0.0) {
throw new ForbiddenItemException("违禁物品:硫磺重量为" + weight + "。禁止携带!");
} else {
totalWeight += weight;
if (totalWeight > 20.0) {
throw new OverweightException("非违禁品总重量为" + totalWeight + "超过20kg,超出部分请托运!");
}
}
if (name.startsWith("forbidden_")) {
forbiddenItemCount++;
}
}
public double getTotalWeight() {
return totalWeight;
}
public int getForbiddenItemCount() {
return forbiddenItemCount;
}
}
public class Main {
public static void main(String[] args) {
Luggage luggage = new Luggage();
try {
luggage.addItem("book", 1.0);
luggage.addItem("laptop", 2.5);
luggage.addItem("clothes", 5.0);
luggage.addItem("forbidden_liquid", 0.1);
luggage.addItem("forbidden_solid", 0.2);
luggage.addItem("diesel", 0.5);
luggage.addItem("more_clothes", 12.95);
} catch (ForbiddenItemException e) {
System.out.println(e.getMessage());
} catch (OverweightException e) {
System.out.println(e.getMessage());
}
System.out.println("非违禁品总重量为" + luggage.getTotalWeight() + "kg,包含违禁品" + luggage.getForbiddenItemCount() + "件。");
}
}