0

What I'm trying to do I'm trying to this product of the values of 2 arrays. But I'm getting this error and I don't know how to fix this. Any help please? Here is my code:

public class This
{
    public int InternProduct(int vector1, int vector2)
    {
        int v1 []= new int[vector1], v2[] = new int[vector2];
        int mult = 0, n = 0;

        for(int i=0;i<=10;i++)
        {
            if(n<vector1)
                n=vector1;
            if(vector1<vector2)
                n=vector2;

            if(i==10)
            {
                for(int j = 1; j <= n; j++)
                        mult += (v1[j]*v2[j]);
            }
        }
        return mult;
    }
}
fvu
  • 32,488
  • 6
  • 61
  • 79
  • 1
    You can fix it by ensuring that j+1 never gets bigger than the smallest of vector1 or vector2 - but are you sure that that is what you want? That being said, there's something really smelly in your code: for i 1 to 9 there's not a lot going on except setting n, are you sure that that's what you want? – fvu Oct 07 '17 at 22:44
  • Another hint: as Java arrays are zero-based, constructs like `for(int i=0;i<=10;i++)` (the i<=10 bit) should, in my opinion, not be used as they are confusing. In this case, the loop will be executed 11 times. If you actually want to execute it 11 times, writing `for(int i=0;i<11;i++)` much better conveys your intentions – fvu Oct 07 '17 at 22:50
  • When you get an array out of bounds error, it might also help to try logging out the index value to the console -- then you might see something is causing the index value to fall outside the bounds _[0, size)_. – Poosh Oct 10 '17 at 06:09

0 Answers0