Question

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:

  1. Output the last value in the Arraylist.

  2. Intentionally insert an out of bounds index value with system.out (index (4) in this case)

  3. 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));
    }
}

}

Was it helpful?

Solution

Check for array index to avoid outofbounds exception: In a given ArrayList, you can always get the length of it. By doing a simple comparison, you can check the condition you want. I haven't gone through your code, below is what i was talking-

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top