2013-09-29 38 views
0

我對Java仍然很陌生,所以我有一種感覺,我做得比我需要的更多,並希望得到任何關於是否有更高效的方法的建議去做這件事。這是我想要做的:檢查數組索引以避免outofbounds異常

  1. 輸出Arraylist中的最後一個值。

  2. 故意插入(在這種情況下指數(4))的出界指標值與System.out的

  3. 繞道不正確的值,並提供最後一個有效的ArrayList值(我希望這是有道理的)。

我的程序運行正常(我加入更晚,所以userInput最終會被使用),但我想這樣做沒有用一個try/catch/finally塊(即檢查索引如果可能的話)。謝謝大家!

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 

public class Ex02 { 

public static void main(String[] args) throws IOException { 

    BufferedReader userInput = new BufferedReader(new InputStreamReader(
      System.in)); 

    try { 
     ArrayList<String> myArr = new ArrayList<String>(); 
     myArr.add("Zero"); 
     myArr.add("One"); 
     myArr.add("Two"); 
     myArr.add("Three"); 
     System.out.println(myArr.get(4)); 

     System.out.print("This program is not currently setup to accept user input. The last  printed string in this array is: "); 

    } catch (Exception e) { 

     System.out.print("This program is not currently setup to accept user input. The requested array index which has been programmed is out of range. \nThe last valid string in this array is: "); 

      } finally { 
     ArrayList<String> myArr = new ArrayList<String>(); 
     myArr.add("Zero"); 
     myArr.add("One"); 
     myArr.add("Two"); 
     myArr.add("Three"); 
     System.out.print(myArr.get(myArr.size() - 1)); 
    } 
} 

}

+0

只是首先檢查ArrayList的長度。 –

回答

1

檢查數組索引,以避免outofbounds例外: 在一個給定的ArrayList,你總是可以得到它的長度。通過做一個簡單的比較,你可以檢查你想要的條件。我沒有通過你的代碼,下面是我在說什麼 -

public static void main(String[] args) { 
    List<String> list = new ArrayList<String>(); 
    list.add("stringA"); 
    list.add("stringB"); 
    list.add("stringC"); 

    int index = 20; 
    if (isIndexOutOfBounds(list, index)) { 
     System.out.println("Index is out of bounds. Last valid index is "+getLastValidIndex(list)); 
    } 
} 

private static boolean isIndexOutOfBounds(final List<String> list, int index) { 
    return index < 0 || index >= list.size(); 
} 

private static int getLastValidIndex(final List<String> list) { 
    return list.size() - 1; 
} 
+0

謝謝你,拉維。這是我所擁有的,但我仍然遇到outOfBounds錯誤。嗯..... – user2825293

+0

在執行'myArr.get(4)'之前,只需調用'isIndexOutOfBounds(myArr,4)',如果返回true,那麼你可以調用'getLastValidIndex(myArr)'得到最後一個有效索引,那麼你可以安全地調用'myArr.get(getLastValidIndex(myArr))'方法。如果不清楚,請發佈完整的代碼。 –

+0

謝謝!這工作。 :) – user2825293