我对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的长度。 –