2013-09-29 35 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