问题描述
我需要将此for循环转换为while循环,以便我可以避免使用中断。
I need to convert this for loop into a while loop so I can avoid using a 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++;
}
推荐答案
此解决方案提供相同的输出作为for循环:
this solution gives the same output as the for loop:
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++;
}
}
说明:
在for循环中使用break语句,因此在程序到达中断后没有任何反应。所以 array [index] = x;
没有被执行。
On the for loop you use the break statement so nothing happens after the program hits the break. So array[index] = x;
didn't get executed.
在while循环中因为没有中断,循环继续,所以语句 array [index] = x;
和 index ++;
已执行。
On the while loop since there's no break, the loop continues, so the statements array[index] = x;
and index++;
got executed.
这就是你得到不同结果的原因。如果你不想要陈述
That's why you got different results. If you don't want the statements
array[index] = x;
index++;
要执行,您只需将if语句设为if / else语句,如上所述。
To be executed you can simply make your if statement a if/else statement as above.
这篇关于在Java中将for循环转换为while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!