array out of bounds exception

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Japhet
    New Member
    • Aug 2012
    • 1

    array out of bounds exception

    Everytime i input a number it gives me the array out of bounds Eception error : 3 and hihglights the product = product * A{i} bit i would be grateful for any help.

    public class Accumulator {
    private int[] A;

    public Accumulator(int[] X) {
    A= new int[X.length];
    for (int i=0; i<X.length; i++)
    A[i] = X[i];
    }

    public int prodA(int m) {

    int product= 1;

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

    product = product * A[i];
    }

    if(product<=m)
    {
    return product;
    }

    if(product>m)
    {
    return m;
    }

    if (product == 0)
    {
    return 0;
    }

    return 0;



    }

    }
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    look at "A.length+1 " in your source code. You have to correct that. Why?

    Assume, the length of A is 3.
    So what is the value of the index i in the last iteration of your loop?
    (Yes, it's 3!)
    But you can only access A[0], A[1] and A[2]. (3 elements). and it crashes with an index-out-of-bounds-exception when you try to acces A[3].

    Comment

    Working...