For this Assignment, submit the following program: The following code causes an
ID: 645494 • Letter: F
Question
For this Assignment, submit the following program:
The following code causes an exception error:
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));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.println(myArr.get(4));
}
}
Starting with this provided code, add the following functionality:
Use a Try/Catch block so that the exception is caught and the program exits a bit more gracefully. Save this file as TryCatch.java. (Be sure to rename the Public Class accordingly.)
Starting with the provided code again (without the Try/Catch block), fix the code so that it runs correctly. That is to say, it should display the last item in the ArrayList. Save this file as Fixed.java. (Be sure to rename the Public Class accordingly.)
Explanation / Answer
TryCatch.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class TryCatch{
public static void main(String[] args) throws IOException {
try{
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.println(myArr.get(4));
}catch(IndexOutOfBoundsException indexOutOfBoundsException )
{
System.out.println("Please see that the index is within the range");
}
}
}
output:
Please see that the index is within the range
Fixed.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Fixed {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.println(myArr.get(3));
}
}
Output:
Three