[英]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.