2016-11-09 69 views
0

我有任务建立一个方法来搜索数组中的变量的相同值。 当有匹配时,该方法将返回索引 - 位置,否则应返回-1。使用while循环搜索数组中的特定值

我的方法在匹配时有效,但当没有任何匹配时我收到错误。

到目前为止我的代码:

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

} 

感谢您的帮助。 菲尔

+0

什么是错误? – Bathsheba

回答

1

它应该是

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

假设阵列具有10个元素。它们的索引从0到9.当你到达最后,用你的代码,你会认为索引为10,不存在,并且你有错误。

+0

那indexoutofbound通过 –