通过实现Runnable接口方式模拟龟兔赛跑。 具体要求如下: 1、100米赛跑,兔子每秒跑2米,乌龟每秒跑1米。 2、兔子在跑过80米的时候,每跑2米休息2秒钟,乌龟每跑1米休息0.1秒。
时间: 2024-11-22 19:47:54 浏览: 12
我们可以使用Java实现一个简单的模拟,首先创建一个`Runner`接口和两个实现了该接口的`Rabbit`和`Turtle`类代表兔子和乌龟。然后,我们可以在`Race`类中维护比赛状态并控制休息时间。以下是模拟的代码:
```java
// 创建Runner接口
interface Runner {
void startRun();
void stopRun();
void rest();
}
// 定义乌龟和兔子的实现类
class Turtle implements Runner {
private double distance;
private boolean isRunning = false;
@Override
public void startRun() {
isRunning = true;
System.out.println("Turtle starts running at 1 meter per second.");
}
@Override
public void stopRun() {
isRunning = false;
System.out.println("Turtle stops running.");
}
@Override
public void rest() {
if (isRunning) {
double restingTime = distance / 10; // 1m休息0.1秒
System.out.println("Turtle rests for " + restingTime + " seconds.");
}
}
// 这里可以根据需求添加继续前进的方法
}
class Rabbit implements Runner {
private double distance, restInterval = 2; // 每跑2米休息2秒
@Override
public void startRun() {
isRunning = true;
System.out.println("Rabbit starts running at 2 meters per second.");
}
@Override
public void stopRun() {
isRunning = false;
System.out.println("Rabbit stops running.");
}
@Override
public void rest() {
if (isRunning) {
if (distance % restInterval == 0) {
double restingTime = restInterval; // 每跑restInterval米休息restInterval秒
System.out.println("Rabbit rests for " + restingTime + " seconds.");
}
}
}
// 跑步方法,假设兔子每次增加速度
public void move(double distance) {
this.distance += distance;
rest(); // 先休息再继续跑
}
}
// 主类 Race
public class Race {
public static void main(String[] args) {
int totalDistance = 100;
double rabbitSpeed = 2, turtleSpeed = 1;
Rabbit rabbit = new Rabbit();
Turtle turtle = new Turtle();
// 同时开始跑步
rabbit.startRun();
turtle.startRun();
// 控制比赛进程
while (turtle.distance < totalDistance && rabbit.distance < totalDistance) {
double timeToMove = Math.min(rabbit.distance / rabbitSpeed, turtle.distance / turtleSpeed);
rabbit.move(timeToMove);
turtle.move(timeToMove);
// 根据兔子的休息规则休息
rabbit.rest();
}
// 结束游戏,打印最终成绩
System.out.println("The race is over! Rabbit wins with a distance of " + rabbit.distance + " meters.");
}
}
```
阅读全文