(4)编写程序模拟两个村庄公用同一口水井。编写Village类模拟村庄,该类中有一个静态变量描述水井中的水量,一个静态方法查看水井中的水量。在主类中创建两个村庄,一个村庄喝了井中的水,另一个村庄查看水量少了。
时间: 2024-02-13 12:03:49 浏览: 76
好的,以下是你要求的代码:
```java
class Village {
static int waterInWell = 1000;
static void checkWaterInWell() {
System.out.println("Water in the well: " + waterInWell + "L");
}
void drinkWater(int amount) {
waterInWell -= amount;
System.out.println("Drank " + amount + "L of water from the well.");
}
}
public class Main {
public static void main(String[] args) {
Village village1 = new Village();
Village village2 = new Village();
village1.drinkWater(500);
Village.checkWaterInWell();
village2.drinkWater(300);
Village.checkWaterInWell();
}
}
```
运行以上代码,输出结果如下:
```
Drank 500L of water from the well.
Water in the well: 500L
Drank 300L of water from the well.
Water in the well: 200L
```
希望对你有所帮助!
阅读全文