PhilS PhilS - 1 year ago 79
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);


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

// here is the problem
return -1;


Thanks for your help.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download