2016-11-09 30 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通過 –