没有输出到我的程序,只是说“运行......”

时间:2015-05-05 03:55:35

标签: java

我知道sumOfMultiples方法本身有效,问题在于main方法。当我运行它时,没有任何反应,只是持续运行。如果这有所不同,我正在使用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;
 }
}

很抱歉,如果这是一个愚蠢的问题,几分钟前就开了帐。

2 个答案:

答案 0 :(得分:3)

你的第二个while循环没有增加num2(这就是为什么它不会停止)

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

答案 1 :(得分:2)

它处于无限循环中:

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 ++,这可能允许它在有限循环后返回。