[英]Converting for loop to while loop in Java
I need to convert this for loop into a while loop so I can avoid using a break. 我需要将此for循环转换为while循环,以便我可以避免使用break。
double[] array = new double[100];
Scanner scan = new Scanner(System.in);
for (int index = 0; index < array.length; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
break;
}
array[index] = x;
}
This is what I came up with but I'm getting a different output: 这是我想出来的,但我得到了不同的输出:
int index = 0;
double x = 0;
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
array[index] = x;
index++;
}
Change 更改
if (x < 0)
{
count--;
}
array[index] = x;
index++;
to something like 喜欢的东西
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
If you want to avoid break, changing the for loop into a while loop doesn't help in any way. 如果你想避免中断,将for循环更改为while循环对任何方式都无济于事。
How about this solution: 这个解决方案怎么样:
boolean exitLoop = false;
for (int index = 0; index < array.length && !exitLoop; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
exitLoop = true;
}
else {
array[index] = x;
}
}
this solution gives the same output as the for loop: 此解决方案提供与for循环相同的输出:
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
}
EXPLANATION: 说明:
On the for loop you use the break statement so nothing happens after the program hits the break. 在for循环中,您使用break语句,因此在程序遇到中断后没有任何反应。 So array[index] = x;
所以array[index] = x;
didn't get executed. 没有得到执行。
On the while loop since there's no break, the loop continues, so the statements array[index] = x;
在while循环中,因为没有中断,循环继续,所以语句array[index] = x;
and index++;
和index++;
got executed. 被处决了
That's why you got different results. 这就是你得到不同结果的原因。 If you don't want the statements 如果你不想要这些陈述
array[index] = x;
index++;
To be executed you can simply make your if statement a if/else statement as above. 要执行,您只需将if语句设为if / else语句,如上所述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.