Sunday, 29 September 2013

Check for array index to avoid outofbounds exception

Check for array index to avoid outofbounds exception

I'm still very new to Java, so I have a feeling that I'm doing more than I
need to here and would appreciate any advise as to whether there is a more
proficient way to go about this. Here is what I'm trying to do:
Output the last value in the Arraylist.
Intentionally insert an out of bounds index value with system.out (index
(4) in this case)
Bypass the incorrect value and provide the last valid Arraylist value (I
hope this makes sense).
My program is running fine (I'm adding more later, so userInput will
eventually be used), but I'd like to do this without using a
try/catch/finally block (i.e. check the index length) if possible. Thank
you all in advance!
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));
}
}
}

No comments:

Post a Comment