shohamh
shohamh

Reputation: 317

Java - java.lang.ArrayIndexOutOfBoundsException

I'm trying to run my code and it says something about the exception:

java.lang.ArrayIndexOutOfBoundsException

I googled it, from what I understand it happens when I try to access an index that's negative or greater than my array length. But I can't seem to find the problem, here's my code: http://pastebin.com/sXsBbYfh

Thanks for any helpers.

EDIT: the error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Calculator.addOne(Calculator.java:127)
at Calculator.add(Calculator.java:88)
at Program.main(Program.java:8)

About the relevant part of the code, I have no idea, that's why i'm coming to you.

Upvotes: 0

Views: 2587

Answers (2)

Mukul Goel
Mukul Goel

Reputation: 8467

This part of code :

public int[] addOne(int arrayIndex)

 124.
        {

 125.
                switch(arrResult[arrayIndex])

 126.
                {

 127.
                        case 0:

 128.
                                arrResult[arrayIndex] = 1;

Is source of error.

Note that.

In java, arrays index range from 0 to length-1

In your code above, when method addon() is called , you are passing array length as parameter, and in code above you are trying to access array[length] which does not exist and hence the exception. Thus you may want to keep that length-1

In the following code line #86

    arrResult = this.addOne(arrResult.length);

There are lot of logical errors in your code. This is just the one that throws the exception you mentioned

Upvotes: 0

jco.owens
jco.owens

Reputation: 535

The issue would appear to be with line 86

  arrResult = this.addOne(arrResult.length);

Array indexes are 0 based, so 0 - length-1 and you are passing length in and then using that to access your array on line 127

  switch(arrResult[arrayIndex])

Upvotes: 3

Related Questions