使用while循环在数组中搜索特定值

时间:2016-11-09 15:47:05

标签: java arrays while-loop

我的任务是构建一个方法来为数组中的变量搜索相同的值。 当匹配时,该方法将返回index-Position,否则它将返回-1。

我的方法在匹配时有效,但是在没有匹配时我会收到错误。

我的代码到目前为止:

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;
    }

}

感谢您的帮助。 菲尔

1 个答案:

答案 0 :(得分:1)

应该是

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

假设数组有10个元素。它们的索引编号为0到9.当你到达最后,使用你的代码时,你会认为索引为10的那个,不存在,并且你有错误。