陷入无限循环? (JAVA)

时间:2017-01-04 18:35:58

标签: java

编程和处理一些Project Euler问题的新手。我相信我陷入了无限循环。我已经在纸上完成了,一切似乎都没问题。我错过了什么?

public class Euler2 {
    public static void main(String[] args) {
        int i = 1;
        int j = 2;
        int fib = 0;
        int sum = 2;

        //Sum of even Fibonacci numbers

        while(fib < 10);{
            fib = (i + j);
            if(fib % 2 == 0);{
                sum = sum + fib;
            }
            i = j; j = fib;
        }   
        System.out.println(sum);        
    }
}

2 个答案:

答案 0 :(得分:1)

你在while条件和花括号之间有一个分号,它不应该存在,也许这就是导致问题的原因。

答案 1 :(得分:-1)

此代码应该有效。

public static void main(String[] args) {
    int i = 1;
    int j = 2;
    int fib = 0;
    int sum = 2;

    //Sum of even Fibonacci numbers

    while(fib < 10){
        fib = (i + j);
        System.out.println( "fib value is: " + fib); 

        if(fib % 2 == 0){
            sum = sum + fib;
        }
        i = j; j = fib;
    }   
    System.out.println("total sum is: " + sum);        
}