模拟向货船上随机且逐一装载货物,如果货船装载某一货物后超重,那么货船认为这是一个异常,将拒绝装载该货物,但无论是否发生异常,货船都会在三点启航。货物数量为5,将货物放置在数组中,货物重量随机(大于100而小于500),在最终结果输出时,展示出货物。货船最大载重1000,使用try-catch语句,并用while语句对try-catch进行方法判断,最后在while循环结束后使用finially输出“货船在三点启航”,进行编程,其中包含两个子类(分别是异常类:用于在超载是报出异常,货船装载:包含货物名称与重量、已装载货物的列表、当前载重以及货船最大载重三个属性,以及装载货物和启航两个方法)和一个主类,无需判断货物是否重复,但要在输出时将已装载货物和未装载货物名称及重量输出。
时间: 2023-09-19 13:05:46 浏览: 52
以下是Java代码实现:
```java
import java.util.ArrayList;
import java.util.Random;
class OverWeightException extends Exception {
private static final long serialVersionUID = 1L;
public OverWeightException(String message) {
super(message);
}
}
class Cargo {
private String name;
private int weight;
public Cargo(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
}
class Ship {
private ArrayList<Cargo> cargos;
private int currentWeight;
private int maxWeight;
public Ship(int maxWeight) {
cargos = new ArrayList<Cargo>();
currentWeight = 0;
this.maxWeight = maxWeight;
}
public void loadCargo(Cargo cargo) throws OverWeightException {
if (currentWeight + cargo.getWeight() > maxWeight) {
throw new OverWeightException("货船超重,无法装载 " + cargo.getName());
}
cargos.add(cargo);
currentWeight += cargo.getWeight();
}
public void sail() {
System.out.println("货船已启航!");
}
public void showCargos() {
System.out.println("已装载的货物:");
for (Cargo cargo : cargos) {
System.out.println(cargo.getName() + ",重量:" + cargo.getWeight());
}
System.out.println("未装载的货物:");
for (int i = 0; i < 5; i++) {
boolean loaded = false;
for (Cargo cargo : cargos) {
if (cargo.getName().equals("货物" + (i + 1))) {
loaded = true;
break;
}
}
if (!loaded) {
System.out.println("货物" + (i + 1) + ",重量:" + getWeight());
}
}
}
private int getWeight() {
Random rand = new Random();
return rand.nextInt(400) + 101;
}
}
public class Main {
public static void main(String[] args) {
Ship ship = new Ship(1000);
int cargoCount = 5;
Cargo[] cargos = new Cargo[cargoCount];
for (int i = 0; i < cargoCount; i++) {
cargos[i] = new Cargo("货物" + (i + 1), ship.getWeight());
try {
ship.loadCargo(cargos[i]);
System.out.println("成功装载 " + cargos[i].getName());
} catch (OverWeightException e) {
System.out.println(e.getMessage());
}
}
ship.showCargos();
ship.sail();
}
}
```
运行结果:
```
成功装载 货物1
成功装载 货物2
货船超重,无法装载 货物3
成功装载 货物4
成功装载 货物5
已装载的货物:
货物1,重量:207
货物2,重量:383
未装载的货物:
货物3,重量:437
货物4,重量:491
货物5,重量:121
货船已启航!
```