Question: Scenario You are a software developer and your client uses a program that stores the odd values in an array. You know that using arrays

Scenario
You are a software developer and your client uses a program that stores the odd values in an array. You know that using arrays may also create an exception error when trying to access an index of an array when that index is out of bounds. In this exercise, the program will request an array size from the user, as well as the values, and an index. Using the try and catch block to handle array index out of bounds exception handling that may occur.
Instructions
In this exercise you will use try and catch blocks to handle an array out of bounds error - ArrayOutOfBoundsException from crashing the program.
An example of the program is shown below:
Enter the size of the array >>10
Enter 10 integers >>
1
3
5
7
9
11
13
15
17
19
Enter an index to retrieve >>
10
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10import java.util.Scanner;
public class BonusBug10{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array >>");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter "+ size +" integers >>");
for (int i =0; i < size; i++){
array[i]= scanner.nextInt();
}
System.out.print("Enter an index to retrieve >>");
int index = scanner.nextInt();
try {
int value = array[index];
System.out.println("Value at index "+ index +" is: "+ value);
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bounds error: "+ e.getMessage());
}
scanner.close();
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!