我需要将这个 for 循环转换为 while 循环,这样我就可以避免使用中断。
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;
}
这是我想出的,但我得到了不同的输出:
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 循环相同的输出:
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语句,因此程序到达break后不会发生任何事情。所以array[index] = x;
没有被处决。
在 while 循环中,由于没有中断,因此循环继续,因此语句array[index] = x;
and index++;
被处决了。
这就是为什么你得到不同的结果。如果您不想要这些声明
array[index] = x;
index++;
要执行,您只需将 if 语句设置为上面的 if/else 语句即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)