Siti Nur
Siti Nur

Reputation: 11

Why does my code output differently from what I expected in Java?

I am learning Java. The following program is supposed to examine a number and determine how many factors (even divisors) that number has. For instance,

1 has only itself as a factor. 5 has 3 factors: 1 and 5. 9 has 3 factors: 1, 3, and 9.

I supply the program with those three numbers in a list. I expect the output to be

{1, 2, 3}

However, what I get is the original number printed that many times:

{1, 5, 5, 9, 9, 9}

What did I do wrong?

int totalFactor(int[] n){
    int tally =0;
        for (int i = 0; i < n.length; i++){ 
        for(int j = 1; j <= n[i]; j++){
            if((n[i] % j) == 0){
                tally++;
            }
        }
    }
    return tally;
}

int[] factorsOfEach(int[] num){
    int[] factor = new int[totalFactor(num)];
    int count = 0;

    for(int i = 0; i < num.length; i++){
        for(int j = 1;j <= num[i]; j++){
            if(num[i] % j == 0){
                factor[count] = num[i];
                count++;
            }
        }
    }
    return factor;
}

Upvotes: 0

Views: 60

Answers (1)

Prune
Prune

Reputation: 77910

The problem is in the middle of your inner loop. What you actually do is, every time you find a factor, you append the original number to the end of the list.

Instead, you should simply keep that count. When you've found all the factors, just append the count once to the end of the list.

for(int i = 0; i < num.length; i++){  // for each number in input list
    count = 0         // haven't found any factors yet for this number
    for(int j = 1; j <= num[i]; j++){  // for each potential factor
        if(num[i] % j == 0){
            count++;  // found one more factor
        }
    } // done with that potential factor
    factor[i] = count;
} // done with that number in the input list
return factor;

Upvotes: 1

Related Questions