用java解决空酒瓶换酒问题
时间: 2023-12-17 21:06:02 浏览: 114
换瓶子问题,简单的c语言逻辑,侵删
空酒瓶换酒的问题可以使用Java语言来解决,具体的解决思路如下:
1. 定义一个酒瓶类 Bottle,包括属性:容量capacity、剩余量remain。
2. 定义一个酒类 Wine,包括属性:名称name、价格price、容量capacity、剩余量remain。
3. 定义一个酒瓶工厂类 BottleFactory,包括方法:
- createBottle(int capacity):创建一个容量为capacity的酒瓶对象,并返回。
- fillBottle(Bottle bottle, Wine wine):将酒瓶bottle中剩余的酒倒入酒wine中,然后将酒wine倒入酒瓶bottle中,返回倒入的酒的容量。
4. 定义一个酒店类 Hotel,包括属性:名称name、酒列表wines、酒瓶列表bottles。
5. 定义一个空酒瓶换酒的方法 exchangeWine(Hotel hotel),实现以下逻辑:
- 遍历酒店的酒瓶列表,找到第一个剩余量为0的酒瓶bottle。
- 遍历酒店的酒列表,找到第一个剩余量不为0的酒wine。
- 调用BottleFactory的fillBottle方法,将酒瓶bottle中剩余的酒倒入酒wine中,然后将酒wine倒入酒瓶bottle中。
- 如果倒入的酒的容量等于酒瓶的容量,则将酒瓶从酒瓶列表中删除,将酒添加到酒列表中。
- 返回是否成功换酒的标志。
代码示例:
```java
public class Bottle {
private int capacity;
private int remain;
public Bottle(int capacity) {
this.capacity = capacity;
this.remain = capacity;
}
public int getCapacity() {
return capacity;
}
public int getRemain() {
return remain;
}
public void setRemain(int remain) {
this.remain = remain;
}
}
public class Wine {
private String name;
private double price;
private int capacity;
private int remain;
public Wine(String name, double price, int capacity) {
this.name = name;
this.price = price;
this.capacity = capacity;
this.remain = capacity;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getCapacity() {
return capacity;
}
public int getRemain() {
return remain;
}
public void setRemain(int remain) {
this.remain = remain;
}
}
public class BottleFactory {
public Bottle createBottle(int capacity) {
return new Bottle(capacity);
}
public int fillBottle(Bottle bottle, Wine wine) {
int remain = bottle.getRemain();
int fill = Math.min(remain, wine.getRemain());
wine.setRemain(wine.getRemain() - fill);
bottle.setRemain(bottle.getRemain() - fill);
return fill;
}
}
public class Hotel {
private String name;
private List<Wine> wines;
private List<Bottle> bottles;
public Hotel(String name) {
this.name = name;
this.wines = new ArrayList<>();
this.bottles = new ArrayList<>();
}
public void addWine(Wine wine) {
wines.add(wine);
}
public void addBottle(Bottle bottle) {
bottles.add(bottle);
}
public boolean exchangeWine() {
for (Bottle bottle : bottles) {
if (bottle.getRemain() == 0) {
continue;
}
for (Wine wine : wines) {
if (wine.getRemain() == 0) {
continue;
}
int fill = new BottleFactory().fillBottle(bottle, wine);
if (fill == bottle.getCapacity()) {
bottles.remove(bottle);
wines.add(new Wine(wine.getName(), wine.getPrice(), fill));
}
return true;
}
}
return false;
}
}
```
阅读全文