我對Java仍然很陌生,所以我有一種感覺,我做得比我需要的更多,並希望得到任何關於是否有更高效的方法的建議去做這件事。這是我想要做的:檢查數組索引以避免outofbounds異常
輸出Arraylist中的最後一個值。
故意插入(在這種情況下指數(4))的出界指標值與System.out的
繞道不正確的值,並提供最後一個有效的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));
}
}
}
只是首先檢查ArrayList的長度。 –