在Java中将for循环转换为while循环
我需要将这个for循环转换成while循环,这样就可以避免使用break在Java中将for循环转换为while循环,java,Java,我需要将这个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 = sc
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;
}
double[]数组=新的double[100];
扫描仪扫描=新扫描仪(System.in);
for(int index=0;index
这是我想到的,但我得到了不同的输出:
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++;
}
int索引=0;
双x=0;
而(索引=0)
{
系统输出打印(“样本”+(索引+1)+“:”;
x=scan.nextDouble();
计数++;
if(x<0)
{
计数--;
}
数组[索引]=x;
索引++;
}
更改
if (x < 0)
{
count--;
}
array[index] = x;
index++;
if(x<0)
{
计数--;
}
数组[索引]=x;
索引++;
差不多
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
if(x<0)
{
计数--;
}
其他的
{
数组[索引]=x;
索引++;
}
如果要避免中断,将for循环更改为while循环没有任何帮助
这个解决方案怎么样:
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;
}
}
boolean exitLoop=false;
对于(int index=0;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++;
}
}
要执行的话,你只需把你的if语句变成上面提到的if/else语句。对不起,以上帝的名义,你为什么要1)使用while而不是for,2)避免break?通常这两种意图会使代码更难阅读。。。
array[index] = x;
index++;