You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除Java抛体运动模拟代码中的break语句 求实现方案

移除break语句的实现方案

实现思路

原有代码中break的作用是命中目标或障碍物时立刻终止循环,可通过调整循环终止条件、控制步长增量的执行时机复现完全一致的逻辑,无需使用break:

  1. 将未命中目标、未命中障碍物作为循环继续的必备条件加入while判断逻辑,只要两个命中状态有一个变为true,循环就会自动终止
  2. 仅在未命中任何目标/障碍物时执行时间t的步长累加,和原有break触发时不执行t累加的逻辑完全对齐

修改后完整代码

Scanner sc = new Scanner(System.in);
double g = 1.62, v0, deg = 45;
double inRadians = Math.toRadians(deg);
double t, x, y, x0 = 0, y0 = 0;
boolean hitTarget = false;
boolean hitObstacle = false;
System.out.println("211RDB121 Pauls Daniels Meija 11.grupa");
System.out.print("v0=");
if (sc.hasNextDouble())
    v0 = sc.nextDouble();
    else {
        System.out.println("input-output error");
        sc.close();
        return;
    }
sc.close();
System.out.println("result:");
System.out.println("t \t x \t y");
t = 0.15;
do {
    x = v0 * t * Math.cos(inRadians) + x0;
    y = v0 * t * Math.sin(inRadians) - (g * t * t) / 2 + y0;
    System.out.printf("%3.2f\t%7.3f\t%7.3f\n", t, x, y);
    if (x >= 17 && x <= 20 && y <= 3 && y >= 0) {
        hitTarget = true;
    }
    else if (x >= 7 && x <= 10 && y <= 4 && y >= 0) {
        hitObstacle = true;
    }
    if (!hitTarget && !hitObstacle) {
        t += 0.1;
    }
} while (y >= 0 && !hitTarget && !hitObstacle);
if (hitObstacle) {
    System.out.println("hit the obstacle!");
}
else if (hitTarget)
    System.out.println("the target was destroyed");
else
    System.out.println("shot off the target");
}

内容的提问来源于stack exchange,提问作者dragon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:45:00