小编use*_*293的帖子

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

我对 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) { …
Run Code Online (Sandbox Code Playgroud)

arraylist try-catch-finally indexoutofboundsexception

1
推荐指数
1
解决办法
4571
查看次数