Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following code causes an exception error: import java.io.BufferedReader; imp

ID: 3679730 • Letter: T

Question

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 myArr = new ArrayList(); 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.) Compile, run, and check the results. Submit the following:

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[]) {

try{

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));

ArrayList myArr = new ArrayList();

System.out.println(“Enter array size:”);

int size = userInput.readLine();

myArr.add(“zero”);

myArr.add(“one”);

myArr.add(“two”);

myArr.add(“three”);

string s =” ”;

system.out.println(“Enter string:”);

s = userInput.readLine();

myArr.add(s);

System.out.println(“Array size is:”,size);

System.out.println(“The element is:”, myArr.get(4)); }

catch(ArrayIndexOutOfBoundsException e) {

System.out.println(“Exception thrown:” + e); }

}}

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 myArr = new ArrayList();

System.out.println(“Enter array size:”);

int size = userInput.readLine();

myArr.add(“zero”);

myArr.add(“one”);

myArr.add(“two”);

myArr.add(“three”);

System.out.println(“Array size is:”,size);

System.out.println(“The element is:”, myArr.get(3));

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote