2013-12-13 38 views
0
public class StringArray { 
    private String strArr[]; 

    public StringArray(int capacity) { 
     strArr = new String [capacity]; 
    } 

    public int indexOf(String s) throws StringNotFoundException { 
     for(int i=0;i<strArr.length ;++i) { 
      if (strArr[i].equals(s)) { 
       return i; 
      } else { 
       throw new StringNotFoundException(); 
      } 
     } 
    } 
} 

我想要做的是返回字符串的索引,如果它在數組中,否則拋出異常。投擲自定義異常,如果for循環

但是Eclipse說我必須返回一個int。

所以我應該只是將返回類型更改爲無效或有其他選項?

StringNotFoundException是我編寫的自定義異常。

+0

返回-1,或者如果索引對程序的功能至關重要,則退出-1程序 – turbo

+2

問問自己:如果'strArr.length'爲0,會發生什麼? – crush

+1

另請注意,如果您搜索的字符串不在您陣列的第一個插槽中,您將始終引發異常。 –

回答

6

做這樣

public int indexOf(String s) throws StringNotFoundException { 
    for(int i=0;i<strArr.length ;++i) { 
     if (strArr[i].equals(s)){ 
      return i; 
     } 
    } 
    throw new StringNotFoundException(); 
} 
2

您需要遍歷數組中的每個字符串進行迭代,並僅如果沒有相匹配,拋出該異常。

我想這是你想要什麼:

public int indexOf(String s) throws StringNotFoundException { 
     for (int i = 0; i < strArr.length; ++i) { 
      if (strArr[i].equals(s)) { 
       return i; 
      } 

     } 
     throw new StringNotFoundException(); 

    } 
0

如何:

/** Returns index of String s in array strArr. Returns -1 if String s is not found. */ 
public int indexOf(String s) { 
     for(int i=0;i<strArr.length ;++i) { 
      if (strArr[i].equals(s)){ 
      return i; 
      } 
     return -1; 
} 

予以避免使用異常。

4

爲什麼在這裏返回-1?這裏是代碼:

public int indexOf(String s) throws StringNotFoundException { 
    for(int i=0; i<strArr.length ;++i) { 
     if (strArr[i].equals(s)) { 
      return i; 
     } 
    } 
    throw new StringNotFoundException(); 
} 
0

爲什麼要做到這一點試試這個..

public int indexOf(String s) throws StringNotFoundException { 

     int index = Arrays.binarySearch(strArr ,s); 

     if(index > 0) 
      return index; 
     else 
      throw new StringNotFoundException(); 
    } 

? 。

+0

這需要一個有序的數組。 – zapl