Java编程,如何打破无限循环?
我有这个学习计划,但我找不到如何结束这个循环。你能帮助我吗?我真的找不到如何退出这个循环,我不必使用while函数,也不允许使用break函数Java编程,如何打破无限循环?,java,cycle,Java,Cycle,我有这个学习计划,但我找不到如何结束这个循环。你能帮助我吗?我真的找不到如何退出这个循环,我不必使用while函数,也不允许使用break函数 import java.io.BufferedReader; import java.io.InputStreamReader; public class Ld2141reb130 { public static void main(String[] args) { BufferedReader br = new Buffere
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Ld2141reb130 {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
double g=9.81, a=40;
a = Math.toRadians(a);
double t, x = 0, y=0, v0;
boolean hitTarget=false;
String s;
System.out.println("Artūrs Škutāns IRDBF1 000RDB111");
try {
System.out.print("v0=");
s = br.readLine();
v0 = Double.parseDouble(s);
} catch(Exception e){
System.out.println("input-output error");
return;
}
System.out.println("t \t x \t y");
t = 0.05;
while (hitTarget=true) {
x = v0*t*Math.cos(a);
y = v0*t* Math.sin(a) - (g*t*t)/2;;
System.out.printf("%3.2f\t%7.3f\t%7.3f\n", t, x, y);
if (x>=15 && x<=18 && y<=6 && y>4) {
hitTarget = true;
}
t += 0.05;
}
while ( y>=0 || x>=10 && y>=4 );
if (hitTarget)
System.out.println("the target was destroyed");
else
System.out.println("shot off the target");
}
}
你的问题在于
while (hitTarget=true) {
这会将hitTarget指定为true,然后检查它是否为true
改为
while (hitTarget==true) {
甚至更好
while (hitTarget) {
但是,由于您以hitTarget作为false开始,您可能希望将hitTarget的声明更改为true,或者将循环更改为do while,以获得至少一次执行,并且在某些情况下,hotTarget将设置为false
那么你有一个空循环
while ( y>=0 || x>=10 && y>=4 );
这将是一个无限循环,如果你进入它,因为它不会改变任何状态
也许你想要像这样的东西
do {
x = v0*t*Math.cos(a);
y = v0*t* Math.sin(a) - (g*t*t)/2;;
System.out.printf("%3.2f\t%7.3f\t%7.3f\n", t, x, y);
if (x>=15 && x<=18 && y<=6 && y>4) {
hitTarget = true;
}
t += 0.05;
} while (hitTarget || y>=0 || x>=10 && y>=4 );
其中有两个明显的错误: hitTarget或hitTarget==true时写入 代码中的内容将为hitTarget指定值true;直接将代码翻译成whiletrue 除此之外: b你需要在你的循环中加入一些东西,把hitTarget的值改为false 换句话说:你指示你的循环永远运行;然后你想知道为什么它从未停止过
最后:考虑将代码分解成更小的方法。将使其更易于阅读和理解。我敢打赌,当hitTarget设置为true时,您希望结束循环。要结束该循环,必须检查是否命中目标!=错误: 当击中目标时!=假的 或者简单地说:
一会儿!hitTarget而hitTarget=true{你可能想要while hitTarget==true double equals这是什么while y>=0 | | x>=10&&y>=4;应该做什么?我想你真的想要while!hitTarget,即循环直到目标被击中。循环之后:当y>=0 | | x>=10&&y>=4;,我不知道你想用它做什么。我有这个任务:所以我想展示tret如果命中目标命中绿色或红色字段,则使用给定的speeduser input v0值和射击角度的射击射程循环也应结束,如果命中目标字段或未命中绿色字段,则打印不同的消息。我从给出的示例中复制了大部分代码,但我不擅长Java编程,无法解释每个示例它显示的东西。谢谢你的帮助。顺便说一句!但是现在没有输出数字:即使这样,hitTarget在循环中也不会被设置为false。非常感谢你的帮助!我对Java和编程真的很陌生,所以我很难做到这一点。再次感谢!