0

I have the task to build a method to search for an identical value for a variable in an array. When there is a match, the method will return the index-Position, otherwise it should return -1.

My method works when there is a match, but I get an error when there isn´t any match.

My Code so far:

public class Schleifentest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int [] cherry = {7,5,6,8,9};
        int magNumber = 112;
        int enthalten2 = Schleifentest.sucheWhile(cherry, magNumber);
        System.out.println(enthalten2);


    }

    public static int sucheWhile(int [] array, int a) {
        int i = 0;
        while(i <= array.length) { 
            if (array[i] == a) {
                return i;
            }
            i++;

        }
        // here is the problem
        return -1;
    }

}

Thanks for your help. Phil

1
  • What is the error? Commented Nov 9, 2016 at 15:48

1 Answer 1

1

it should be

while(i < array.length) {...}

suppose that the array has 10 elements. They are indexed from 0 to 9. When you reach the end, with your code, you'll consider the one indexed as 10, that doesn't exist, and you have the error.

Sign up to request clarification or add additional context in comments.

1 Comment

that indexoutofbound through

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.