M Garp - 1 year ago 77

Java Question

I'm trying to answer this question using brute force so I can understand what;s going on:

https://www.interviewcake.com/question/java/product-of-other-numbers

But the problem is I don't understand why my logic is not working. Here is what I tried so far:

`public class EveryInteger {`

public static void main(String[] args) {

int a1[] = {1, 7, 3, 4};

int a2[] = new int[4];

for(int i =0; i<a1.length; i++){

int index = a1[i];

int sum = 0;

for(int j =0; j<a1.length; j++){

if(a1[i]==a1[j]){

continue;

}

sum = index * a1[j];

a2[i] = sum;

System.out.println(a2[i]);

}

}

}

Can anyone please show me how you solve this problem using two for loops?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You're assigning `sum`

to `a2`

and printing it in the inner loop, which is incorrect. Try doing it in the outer loop instead:

```
public class EveryInteger {
public static void main(String[] args) {
int a1[] = {1, 7, 3, 4};
int a2[] = new int[4];
for(int i =0; i<a1.length; i++){
int sum = 1;
for(int j =0; j<a1.length; j++){
if(a1[i]==a1[j]){
continue;
}
sum *= a1[j];
}
a2[i] = sum;
System.out.println(a2[i]);
}
}
}
```