编写java代码 猫和狗共享房屋中的一桶水,猫和狗轮流喝水。水有20个单位,狗每次喝2个单位,猫每次喝1个单位,猫和狗在轮流喝水的过程中,主动休息2秒,当水被喝尽时,既结束。
时间: 2023-05-13 21:05:57 浏览: 64
用java写的小宠物游戏
以下是Java代码:
public class CatDogWaterSharing {
public static void main(String[] args) {
int water = 20;
while (water > 0) {
System.out.println("Water left: " + water);
water -= 2;
if (water <= 0) {
break;
}
System.out.println("Dog drinks 2 units of water.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Water left: " + water);
water -= 1;
if (water <= 0) {
break;
}
System.out.println("Cat drinks 1 unit of water.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Water is all gone.");
}
}
阅读全文