0

Beginner in Android development. My code crashes. I have made a simple Java method like a inArray function in php.

private ArrayList<Long> inArray(int array[], int searched)
{
    ArrayList<Long> ans = new ArrayList<Long>();

    for(int i = 0; i <= array.length; i++)
    {
          if (array[i] == searched)
          {
              ans.add((long) i);
          }
    } 

    return ans;
}

It doesn't work on this stage

if (array[i] == searched)

How can i Compare them ? I have tried many things but the code just keeps crashing. Thank you very much.

5
  • 1
    use i < array.length instead of i <= array.length Commented Jun 27, 2012 at 20:39
  • Cant believe that this little peace of .... was the problem. Interesting why ? Will look in to it. Thank you very much. Commented Jun 27, 2012 at 20:43
  • 1
    array.length returns the number of elements. In a 10 element array, it returns 10, while the elements are 0-9. When it gets to 10, it crashes with an arrayOutOfBounds exception. Commented Jun 27, 2012 at 20:50
  • your problem get solved or not? problem is because you are using i=0 and looping to length-1 Commented Jun 27, 2012 at 20:55
  • my problem got solved Thank you very much! Commented Jun 27, 2012 at 21:13

1 Answer 1

4

use

for(int i = 0; i <array.length; i++)

or

for(int i = 0; i <= array.length-1; i++)

instead of

for(int i = 0; i <= array.length; i++)
Sign up to request clarification or add additional context in comments.

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.