2015-05-05 18 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 ++这样的增量器,这可能会让它在有限循环之后回来。

相关问题