简体   繁体   English

如何跳过Java中while循环的最后一次迭代?

[英]How to skip last iteration of while loop in java?

This is my code: 这是我的代码:

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 + " ");
}

I want to skip the last iteration so that the last number of output does not go beyond the limit. 我想跳过最后一次迭代,以便最后输出的数量不会超出限制。

For example, if I initialise the value of u to 25 , then it will also print 34 which goes out of the limit. 例如,如果我将u的值初始化为25 ,那么它还会打印出超出限制的34 Skipping the last iteration will not display the number 34 . 跳过最后一次迭代将不会显示数字34

Just print before you increment z to the next number in the Fibonacci sequence: 只需在将z递增到斐波那契数列中的下一个数字之前进行打印即可:

while (z < u) {
    System.out.print(z+" ");
    x = y;
    y = z;
    z = x + y;
}

With this change, the final iteration still would result in z being advanced to a value which is too high, and would fail the next iteration, but you would not be printing this number. 进行此更改后,最终的迭代仍然会导致z前进到一个太大的值,并且会使下一个迭代失败,但是您不会打印此数字。

This refactor also takes care of another problem you had, namely not printing the first number in the Fibonacci sequence. 此重构还可解决您遇到的另一个问题,即不打印斐波那契数列中的第一个数字。 By placing the print statement after advancing the number, the initial value of z would never have a chance to be printed. 通过将打印语句推进号码 ,初始值z永远也不会被打印的机会。

how about: 怎么样:

while(z<u)
 {
    x=y;
    y=z;
    z=x+y;
    if (z < u) {
     System.out.print(z+" ");
    }
}

It's the simplest solution, assuming I got the question right... 假设我正确回答问题,这是最简单的解决方案...

while (...) {
   ...
   ...
   if (condition){
      continue; // which skips to the following iteration
      // or
      // break; // which just stops the loop from iterating
}

so the condition in your case could be z<u or you can put the print itself in the if clause 因此您的情况可能是z<u或者您可以将打印本身放在if子句中

Print the current value first, then update z. 首先打印当前值,然后更新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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM