java - “While”循环未执行?

标签 java loops while-loop

我的代码中有一条注释来解释我想要的最终结果是什么,但请不要在回答这个问题时回答我如何实现该目标。

基本上,我有一个标记为“currentNum”的 int,它等于 1。我有一个 while 循环,要执行到 cu​​rrentNum 小于 400 万为止。但是,由于某种原因,循环没有执行。 while 循环之外的所有内容都会执行,但 while 循环本身不会执行。

控制台上显示一次“HI”。 控制台中不显示“LOOP”。

代码:

 /*Each new term in the Fibonacci sequence is generated by adding the previous two terms. 
  * By starting with 1 and 2, the first 10 terms will be:
  * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  * By considering the terms in the Fibonacci sequence whose values do not exceed four million, 
  * find the sum of the even-valued terms.*/

public class Solution {

public static void main(String args[]) {

    int lastNum1 = 0;
    int lastNum2 = 0;
    int currentNumEven = 0;
    int currentNum = 1;
    int sumEven = 0;
    boolean last = true;

    System.out.println("HI");

    while(currentNum < 4000000);

    System.out.println("LOOP");

    currentNum = currentNum + (lastNum1 + lastNum2);

    if(last) {
        lastNum1 = currentNum;
        last = !last;
    } else {
        lastNum2 = currentNum;
        last = !last;
    }

    if(currentNum % 2 == 0) {
        currentNumEven = currentNum;
        sumEven += currentNum;
        System.out.println(currentNumEven);
        System.out.println(currentNum);
    }

    if(currentNum < 4000000) {
    currentNum++;

    } else {
        System.out.println("Sum of all even Fibonacci values: " + sumEven + "\n Last even number of sequence below 4,000,000" + currentNumEven);
      }

   }

}

最佳答案

错误在这一行:

 while(currentNum < 4000000);

最后一个;放错地方了!在 while 条件之后,您应该放置一个开始 {,然后在循环末尾放置另一个 },以关闭该 block 。像这样:

while (currentNum < 4000000) {
    // body
}

关于java - “While”循环未执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226656/

相关文章:

php - WHILE 循环中的 mysqli 查询

java - 输入验证(do-while 循环)出现故障

Java服务器页面: How to get a value into an attribute from code without Expression Language?

php - 查询进入无限循环

无能为力 : Infinite Loop in C

ruby - 在 ruby​​ 中迭代多个数组的优雅简洁的方法是什么?

c - 'while loop' 内存在 C 编程中如何工作?

java - 如何循环调用一个类的所有getter方法?

java - Eclipse编辑java文件并在原文件夹下运行

Java 四舍五入 0.05 钱