PhilS PhilS - 1 month ago 16
Java Question

Searching for specific value in array with while-loop

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

Answer

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.