2015-05-05 21 views
0

我知道sumOfMultiples方法本身的工作原理和問題在於主要方法。當我運行它時,沒有任何反應,它只是連續運行。我使用netbeans如果有所作爲。沒有得到輸出到我的程序,只是說「正在運行...」

package examp; 

public class Main { 

public static void main(String[] args) { 
    Main example = new Main(); 
    System.out.println("The answer is " + example.sumOfMultiples(2, 3)); 
} 

public int sumOfMultiples(int num1, int num2) { 
    int num1Total = 0; 
    int num2Total = 0; 

    //Total of the multiples of the first number. 
    while (num1 < 1000) { 
     num1Total = num1Total + num1; 
     num1 = num1 + num1; 
    } 
    //Total of the multiples of the second number. 
    while (num2 < 1000) { 
     if (num2 % num1 != 0) {   //Makes sure it doesn't add multiples of the first number twice. 
      num2Total = num2Total + num2; 
     } 
    } 

    return num1Total + num2Total; 
} 
} 

對不起,如果這是一個愚蠢的問題,只是在幾分鐘前做了一個帳戶。

+0

爲什麼你不聲明方法是靜態的,並且在不初始化Main實例的情況下使用它? – CSCH

回答

3

你的第二個while循環不遞增num2(這就是爲什麼它不停止)

while (num2 < 1000) { 
    if (num2 % num1 != 0) { 
     num2Total = num2Total + num2; 
    } 
    num2++; // <-- like so. 
    // or, num2 = num2 + 1; 
} 
2

它在無限while循環:

while (num2 < 1000) { 
    if (num2 % num1 != 0) {   //Makes sure it doesn't add multiples of the first number twice. 
     num2Total = num2Total + num2; 
    } 
} 

如果你想在調試自己然後運行這個(我已經添加了幾個System.out.println語句),你會知道如何:

public int sumOfMultiples(int num1, int num2) { 
    int num1Total = 0; 
    int num2Total = 0; 

    //Total of the multiples of the first number. 
    while (num1 < 1000) { 
     num1Total = num1Total + num1; 
     num1 = num1 + num1; 
     System.out.println("num1"+num1); 
    } 
    //Total of the multiples of the second number. 
    System.out.println("num1:"+num1+" "+"num2:"+num2); 
    while (num2 < 1000) { 
     if (num2 % num1 != 0) {   //Makes sure it doesn't add multiples of the first number twice. 
      num2Total = num2Total + num2; 
     } 
    } 

    return num1Total + num2Total; 
} 

用這個你可以得到num1 = 1024 num2 = 3,你可以看到它永遠不會進入if循環,所以第二次while循環進入無限循環。一旦它進入第二個while循環,那麼num2保持不變,所以你需要添加一些像num2 ++這樣的增量器,這可能會讓它在有限循環之後回來。

相關問題