Non*_*one 2 java loops while-loop
我在我的代码中有一个评论来解释我最终的结果是什么,但请不要回答我在回答这个问题时如何实现这个目标.
基本上,我有一个标有"currentNum"的int,它等于1.我有一个while循环,要执行直到currentNum少于四百万.但是,由于某种原因,循环没有执行.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误在这一行:
while(currentNum < 4000000);
Run Code Online (Sandbox Code Playgroud)
那最后一个;是错位的!在while条件之后你应该放置一个开口{,然后}在循环结束时放一个开口,用于关闭块.像这样:
while (currentNum < 4000000) {
// body
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |