0

hello
i want to create two arrays i have the index for them and the size
and have the dot product of a and b
and create a third array that is c[i]=a[i]*b[i]

however i tried to do it but the output doesn't come the correct :(

import java.util.Scanner;
public class JavaApplication09 {

    static Scanner input = new Scanner (System.in);
    public static void main(String[] args) {
    int a [] = {1,2,3,4,5};
    int b [] = {6,7,8,9,3};
    int c [] = null;
    for (int i=0;i<a.length;i++){
    c[i]+= (a[i]*b[i]); 

    }

    }

}

can someone help what i did wrong ??

3
Contributors
3
Replies
26
Views
3 Months
Discussion Span
Last Post by AssertNull
0

Variable c is null, so it’s not an array and line 10 will give a null pointer exception.
You need to initialise c to an array of the right size before you try to set any of its elements.

1

i did everything right but it doesn't work

Not trying to nitpick, but this is a contradiction in terms. I point this out not to be a smart-aleck, but to point out that this isn't the mindset you should be in when debugging. If you are debugging and positive you did everything right, you are unlikely to find the bug.

but the output doesn't come the correct

Again, mindset. When debugging, please be as specific as possible. This helps YOU as well as us. What output were you expecting? What output did you get? How are these outputs different? This approach will help you in the debugging process and also help US.

Line 8 appears to be the culprit here. You have an integer array called c[] that you have assigned to be null. You then use that null array to store values in line 10. You must allocate storage space. In your case, your loop control variable i in line 9 is based on a.length. Thus the array c[] must be at least as long as a[]. Change line 8 to

int c [] = new int[a.length];

Finally, in line 10 you have this...

c[i]+= (a[i]*b[i]);

Perhaps you want THIS (= instead of +=)?

c[i] = (a[i]*b[i]);

The actual EFFECT of that line change may be nothing, but I thing that LOGICALLY if you are ASSIGNING c[] to be the dot product as opposed to INCREMENTING c[] to add the dot product, the code should reflect that. Java will initialize c[] to zeroes so there will be no difference, but for readability and logic, you should choose = or += in a way that makes sense.

Edited by AssertNull

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.