Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Students also viewed these Databases questions