0

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.

13
  • Can you post the relevant part of the code here along with the stack trace? Commented Nov 27, 2012 at 19:01
  • Please. Can you post the stackTrace about this exception?: Commented Nov 27, 2012 at 19:01
  • which code line does the exception gets thrown at? Commented Nov 27, 2012 at 19:01
  • can you please post the line which give the exception. Plus for future reference when you post questions please post the necessary code snippet in the question body. Thanks. Commented Nov 27, 2012 at 19:02
  • 3
    Well, there are hell lot of logical errors in that code. But the one which throws the exception is - this.addOne(arrResult.length);, here you are passing the length of array, and using it as index in the addOne method. Change this invocation to - this.addOne(arrResult.length - );`. Note that, this will not solve all the issue. And I have no courage to pin down every problem here. Commented Nov 27, 2012 at 19:08

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.