输入格式:第一行输入一个大于零的整数或小数,当做货船的最大装载量maxWeight。
第二行输入两个大于零的整数或小数,当做尝试装载上货船的两个集装箱的重量,中间以空格隔开。
package csdn003;
import java.util.Scanner;
/**
* @author wf
*/
public class OverLoadException extends Exception{
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public OverLoadException(double n) {
this.message = "无法再装载重量是" + n + "吨的集装箱";
}
public void showMessage() {
System.out.println(this.message);
}
}
class CargoShip {
private double actualWeight = 0;
private double maxWeight;
public double getActualWeight() {
return actualWeight;
}
public void setActualWeight(double actualWeight) {
this.actualWeight = actualWeight;
}
public double getMaxWeight() {
return maxWeight;
}
public void setMaxWeight(double maxWeight) {
this.maxWeight = maxWeight;
}
public void loading(double weight) throws OverLoadException {
this.actualWeight += weight;
if (actualWeight > maxWeight) {
throw new OverLoadException(weight);
}
System.out.println("目前共装载了" + actualWeight + "吨货物");
}
}
class Main {
public static void main(String[] args) {
CargoShip myship = new CargoShip();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入最大载重量:");
double maxWeight = scanner.nextDouble();
myship.setMaxWeight(maxWeight);
try {
System.out.println("请输入集装箱1的重量:");
double weight1 = scanner.nextDouble();
myship.loading(weight1);
System.out.println("请输入集装箱2的重量:");
double weight2 = scanner.nextDouble();
myship.loading(weight2);
}catch (OverLoadException e) {
e.showMessage();
}finally {
System.out.println("货船将正点起航");
}
}
}