[英]How to skip last iteration of while loop in java?
这是我的代码:
System.out.println("Enter upper limit of range");
long u = in.nextLong(), x = 0, y = 1, z = x+y;
System.out.println("Fibonacci Series till " + u + " -");
System.out.print(x + " " + y + " " + z + " ");
while (z < u) {
x = y;
y = z;
z = x + y;
System.out.print(z + " ");
}
我想跳过最后一次迭代,以便最后输出的数量不会超出限制。
例如,如果我将u
的值初始化为25
,那么它还会打印出超出限制的34
。 跳过最后一次迭代将不会显示数字34
。
只需在将z
递增到斐波那契数列中的下一个数字之前进行打印即可:
while (z < u) {
System.out.print(z+" ");
x = y;
y = z;
z = x + y;
}
进行此更改后,最终的迭代仍然会导致z
前进到一个太大的值,并且会使下一个迭代失败,但是您不会打印此数字。
此重构还可解决您遇到的另一个问题,即不打印斐波那契数列中的第一个数字。 通过将打印语句推进号码后 ,初始值z
永远也不会被打印的机会。
怎么样:
while(z<u)
{
x=y;
y=z;
z=x+y;
if (z < u) {
System.out.print(z+" ");
}
}
假设我正确回答问题,这是最简单的解决方案...
while (...) {
...
...
if (condition){
continue; // which skips to the following iteration
// or
// break; // which just stops the loop from iterating
}
因此您的情况可能是z<u
或者您可以将打印本身放在if子句中
首先打印当前值,然后更新z。
System.out.println("Enter upper limit of range");
long u=in.nextLong(),x=0,y=1,z=x+y;
System.out.println("Fibonacci Series till "+u+" -");
System.out.print(x+" "+y+" ");
while(z<u)
{
System.out.print(z+" ");
x=y;
y=z;
z=x+y;
}
System.out.println("Enter upper limit of range");
long u = in.nextLong(), x = 0, y = 1, z = x+y;
System.out.println("Fibonacci Series till " + u + " -");
System.out.print(x + " " + y + " " + z + " ");
while (true) {
x = y;
y = z;
z = x + y;
if(z>u) {
break;
}
System.out.print(z + " ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.