检查数组索引以避免越界异常

use*_*293 1 arraylist try-catch-finally indexoutofboundsexception

我对 Java 还很陌生,所以我有一种感觉,我在这里做的比我需要做的要多,并且希望就是否有更熟练的方法来解决这个问题提供任何建议。这是我想做的:

  1. 输出 Arraylist 中的最后一个值。

  2. 故意使用 system.out 插入越界索引值(本例中为索引 (4))

  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));
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Rav*_*shi 6

检查数组索引以避免越界异常: 在给定的 中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;
}
Run Code Online (Sandbox Code Playgroud)