Dintefresh
Dintefresh

Reputation: 11

Not getting the output to my program, just says "running..."

I know the sumOfMultiples method itself works and that the problem lies in the main method. When I run it, nothing happens and it just continuously runs. I'm using netbeans if that makes a difference.

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;
 }
}

Sorry if it's a stupid question, just made an account a couple of minutes ago.

Upvotes: 0

Views: 42

Answers (2)

comrench
comrench

Reputation: 248

Its in infinite while loop:

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

If you want to debug on your own then run this (I have added couple of System.out.println statements) and you will know how:

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;
 }

With this you get num1=1024 num2=3 and you can see that it will never go in the if loop so second while loop goes in infinite loop. Once it enters second while loop then num2 remains constant so you need to add some incrementer like num2++ which may allow it to come back after finite loops.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201467

Your second while loop doesn't increment num2 (that is why it doesn't stop)

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

Upvotes: 3

Related Questions