Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck for array index to avoid outofbounds exception
    primarykey
    data
    text
    <p>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:</p> <ol> <li><p>Output the last value in the Arraylist.</p></li> <li><p>Intentionally insert an out of bounds index value with system.out (index (4) in this case)</p></li> <li><p>Bypass the incorrect value and provide the last valid Arraylist value (I hope this makes sense).</p></li> </ol> <p>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!</p> <pre><code>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&lt;String&gt; myArr = new ArrayList&lt;String&gt;(); 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&lt;String&gt; myArr = new ArrayList&lt;String&gt;(); myArr.add("Zero"); myArr.add("One"); myArr.add("Two"); myArr.add("Three"); System.out.print(myArr.get(myArr.size() - 1)); } } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload