java龟兔赛跑小程序
时间: 2023-07-24 21:53:45 浏览: 91
好的,我可以为您提供一个简单的java龟兔赛跑小程序。以下是程序代码:
```
import java.util.Random;
public class TortoiseAndHareRace {
public static void main(String[] args) {
int finishLine = 100;
int tortoisePosition = 1;
int harePosition = 1;
Random random = new Random();
System.out.println("On your mark, get set, GO!");
while (tortoisePosition < finishLine && harePosition < finishLine) {
int tortoiseMove = random.nextInt(10) + 1;
int hareMove = random.nextInt(10) + 1;
// Tortoise's move
if (tortoiseMove >= 1 && tortoiseMove <= 5) {
// Fast plod
tortoisePosition += 3;
} else if (tortoiseMove >= 6 && tortoiseMove <= 7) {
// Slip
tortoisePosition -= 6;
} else {
// Slow plod
tortoisePosition += 1;
}
// Hare's move
if (hareMove >= 1 && hareMove <= 2) {
// Sleep
} else if (hareMove >= 3 && hareMove <= 4) {
// Big hop
harePosition += 9;
} else if (hareMove == 5) {
// Big slip
harePosition -= 12;
} else if (hareMove >= 6 && hareMove <= 8) {
// Small hop
harePosition += 1;
} else {
// Small slip
harePosition -= 2;
}
// Make sure positions are within bounds
if (tortoisePosition < 1) {
tortoisePosition = 1;
}
if (harePosition < 1) {
harePosition = 1;
}
if (tortoisePosition > finishLine) {
tortoisePosition = finishLine;
}
if (harePosition > finishLine) {
harePosition = finishLine;
}
// Print out current positions
for (int i = 1; i <= finishLine; i++) {
if (i == tortoisePosition) {
System.out.print("T");
} else if (i == harePosition) {
System.out.print("H");
} else {
System.out.print("_");
}
}
System.out.println();
}
// Determine winner
if (tortoisePosition >= finishLine && harePosition >= finishLine) {
System.out.println("It's a tie!");
} else if (tortoisePosition >= finishLine) {
System.out.println("Tortoise wins!");
} else {
System.out.println("Hare wins!");
}
}
}
```
这个程序会模拟一场乌龟和兔子赛跑,直到其中一方到达终点。程序会随机生成每个角色的移动,其中兔子有时会睡觉或者跌倒。程序每次运行时都会输出当前的赛道图,并在比赛结束时宣布胜利者。
希望这个程序可以满足您的需求!
阅读全文