2016-02-26 77 views
0

我有一個內置的檢查有效的URL。我已經插入我檢查的一部分。該計劃是讀取一個排名列表,然後打印/排序/搜索。代碼的第一部分是我檢查有效的URL,第二部分是將它插入到一個arrayList。如果我輸入的網址:https://www.ssa.gov/cgi-bin/popularnames.cgi我收到以下錯誤:檢查有效URL

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
at rankings.RankMenu.toArrayList(RankMenu.java:160) 
at rankings.RankMenu.menu(RankMenu.java:84) 
at rankings.Rankings.main(Rankings.java:16) 
Java Result: 1 

160線是:

String test2 = temp[element]; 

代碼傳遞字符串toArrayList是:

Scanner read = new Scanner(text.openStream()); 
while(count < 25){ 
output = read.nextLine(); 

我如何檢查該網址,以避免這種OR調整我的代碼插入一個文件到該ArrayList?這個總計只有菜單中的223行代碼,所以我會通過發佈一切,除非需要幫助。謝謝。

public boolean isValidURL(String url){ 
    try{ 
     java.net.URL file = new java.net.URL(url); 
     this.text = file; 
     return true; 
    } catch (java.net.MalformedURLException ex) { 
     return false; 
    } catch (java.io.IOException ex){ 
     return false; 
    } 
} 

public void toArrayList(String string, int rank, int element){ 
    String[] temp = string.split("\\s+"); 
    String test = temp[rank]; 
    String test2 = temp[element]; 
    String[] newTemp = new String[temp.length - 2]; 
    int cnt2 = 0; 
    for(int cnt = 0; cnt < temp.length; cnt++){ 
     if(temp[cnt] != temp[rank] && temp[cnt] != temp[element]){ 
      newTemp[cnt2] = temp[cnt]; 
      cnt2++; 
     }    
    } 
    String test3 = Arrays.toString(newTemp); 
    textList.add(new Type(test, test2, test3)); 
} 
+0

哪條線是'RankMenu.java:160'? – Atri

+0

你傳遞給'toArrayList'的參數是什麼?當然了'string'參數不是單獨的URL,因爲該字符串不包含在所有的空間和你的分裂將結束與一個單一的元素。 – RealSkeptic

+0

我將在編輯中解決這兩個問題 –

回答

0

檢查rankelement小於temp陣列的長度使用temp[rank]temp[element]訪問它之前。

此外,檢查是否cnt2不斷超越的newTemp長度。

+0

cnt 2不會,它會被限制爲始終處於newTemp的確切索引位置並且永遠不會更大。此代碼可用於除網頁以外的任何類型/大小的文檔。 –