Question: Java Programming My catch block is not working. Why, please? Need help. Thanks Instruction Program 1: Write a program that uses an ArrayList filled with
Java Programming
My catch block is not working. Why, please? Need help. Thanks
Instruction
Program 1: Write a program that uses an ArrayList filled with a minimum of 10 Strings. Use a for-each loop to print the ArrayList collection. Then ask a user which element they would like to see again. Then, attempt printing the element in a try/catch format which will result in the element being display. If the element value received is invalid, display a message that an Exception has been thrown displaying Out of Bounds. In this program, include the use of Autoboxing/Auto-Unboxing, working with a user String input.
Here is my code
import java.io.IOException;
import java.util.*;
public class ArrayListString{
public static void main(String[] args) throws IOException{
//declare ArrayList object and fill with strings
ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mangoes");
fruits.add("Pears");
fruits.add("Orange");
fruits.add("Manderins");
fruits.add("Strawberries");
fruits.add("Kiwifruit");
fruits.add("Watermelon");
fruits.add("Blueberries");
//print elements with for-each loop
System.out.println("ArrayList elements ");
for (String i:fruits) {
System.out.println(i);
}
System.out.println();
//get user input
System.out.print("Which element would you like to see again? ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int index= Integer.valueOf(input);
System.out.println();
//print element
try{
if (index >= 0 && index < fruits.size())
{System.out.println("The element on position "
+ input +" is "+ fruits.get(index));
System.out.println();}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
sc.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
