gpt4 book ai didi

java - 如何在不中断的情况下停止while循环

转载 作者:行者123 更新时间:2023-12-02 09:24:37 26 4
gpt4 key购买 nike

谁能帮帮我。

子弹从大炮中发射出来,一直飞到落地。如果击中目标(红色)则打印“目标已被击中”,如果没有“击中目标”。

Battle area

但主要问题是我无法停止循环,如果我错过了目标,我就无法使用break;根本没有,只有 while、if、else 或 else if。

No hitHit the target

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double g=8.86,a=40,delta_t=0.05; // a=angle
double v0,x,y,t,x0,y0;
boolean hitTarget = false;

System.out.println("191RDB107 Vladislavs Fedotovs");
System.out.println("While operators,07,Urans");

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.1;
while(hitTarget!=true) {

x =v0*t*Math.cos(Math.toRadians(a));
y =v0*t*Math.sin(Math.toRadians(a))-(g*Math.pow(t, 2))/2;
System.out.printf("%3.2f\t%7.3f\t%7.3f\n", t, x, y); // red target
if ((x >= 12 && x <= 17) && (y <=-2 && y >=-4)) {
hitTarget=true;
System.out.print("the target was destroyed");
t+=0.1;
} else if (x<=10 && y<=0 || x>=10 && x<=12 && y>=-4 || x>17 && y>=-4) { // green "grass"
System.out.print("shot off the target");
t+=0.1;
} else {
System.out.print("shot is in the air");
}

t+=0.1;
}

Formula which I'm using

Should be something like that.

**基本上,在子弹击中地面(y)后,它应该停止循环。谢谢!!

最佳答案

不要使用“hitTarget”作为 while 循环条件。将其更改为一个单独的变量,让您知道子弹是否在飞行中。当子弹击中目标时,您可以将“hitTarget”设置为 true 以供稍后使用。如果子弹击中目标或者击中草地,可以将bulletInFlight设置为false来退出循环。

boolean bulletInFlight = true;
boolean hitTarget = false;
while (bulletInFlight) {
x =v0*t*Math.cos(Math.toRadians(a));
y =v0*t*Math.sin(Math.toRadians(a))-(g*Math.pow(t, 2))/2;
System.out.printf("%3.2f\t%7.3f\t%7.3f\n", t, x, y); // red target
if ((x >= 12 && x <= 17) && (y <=-2 && y >=-4)) {
bulletInFlight = false;
hitTarget = true;
System.out.print("the target was destroyed");
t+=0.1;
} else if (x<=10 && y<=0 || x>=10 && x<=12 && y>=-4 || x>17 && y>=-4) {
bulletInFlight = false;
System.out.print("shot off the target");
t+=0.1;
} else {
System.out.print("shot is in the air");
t+=0.1;
}
}
// Now do whatever you need to do once you know the target has been hit or not hit.

关于java - 如何在不中断的情况下停止while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com