java编写程序实现青蛙跳井游戏,并统计100次游戏和1000次游戏的时长及成功率。
时间: 2024-09-25 21:07:36 浏览: 107
在Java中编写青蛙跳井游戏并统计次数的时长和成功率,我们可以创建一个计时器来记录游戏次数和总时间,同时通过一个标志或变量来跟踪青蛙跳出井口的成功情况。以下是一个简化版的示例代码:
```java
import java.util.concurrent.TimeUnit;
class FrogWell {
private int wellDepth = 20;
private int jumpSteps = 3;
private int currentHeight = 0;
private boolean success = false;
private long startTime;
public void startJump(int numTrials) {
startTime = System.nanoTime(); // 记录开始时间
for (int i = 0; i < numTrials; i++) {
playGame();
if (isSuccessful()) {
success = true;
}
}
long endTime = System.nanoTime();
long elapsedTime = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
// 统计数据
double successRate = success ? (double) success / numTrials : 0;
System.out.printf("100次游戏耗时: %.2f ms\n", elapsedTime / 100);
System.out.printf("1000次游戏耗时: %.2f ms\n", elapsedTime / 1000);
System.out.printf("100次游戏成功率: %.2f%%\n", successRate * 100);
}
private boolean isSuccessful() {
return currentHeight >= wellDepth;
}
private void playGame() {
while (currentHeight < wellDepth) {
for (int j = 0; j < jumpSteps; j++) {
currentHeight++;
}
// 模拟滑落...
}
System.out.println("青蛙成功跳出井口");
}
}
public class Main {
public static void main(String[] args) {
FrogWell frog = new FrogWell();
frog.startJump(100); // 100次游戏
frog.startJump(1000); // 1000次游戏
}
}
```
阅读全文