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

This program will simply read in ONE value and display the appropriate exception

ID: 640242 • Letter: T

Question

This program will simply read in ONE value and display the appropriate exception, OR the value in the array.

Create an array with 5 elements (it can be int, string, or anything you want)

Prompt the user to enter an index number.

If the value entered is NOT an integer then display "You did not enter an integer value"

If the value entered results in an out of bound exception display "Index should be between 1 and 5"

If the value is valid, then simply print out the element of the array (it could be city names, exam grades etc.)

You will need to catch two different exceptions in your code:

ArrayIndexOutOfBoundsException

NumberFormatException

To determine if a value is an integer, you can use Integer.parseInt() with a String argument.

Explanation / Answer

import java.util.InputMismatchException;
import java.util.Scanner;

public class ArrayException {
   public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       int[] arr = { 2, 4, 9, 6, 1 };
       System.out.print("Enter an index value: ");
       try {
           int index = in.nextInt();
           try {
               System.out.println("Value at index " + index + " is " + arr[index]);
           } catch (ArrayIndexOutOfBoundsException e) {
               System.out.println("Index should be between 0 and 4");
           } catch (NumberFormatException e) {
               System.out.println("Entered Number is not an integer");
           }
       } catch (InputMismatchException e) {
           System.out.println("You did not enter an Integer value");
       }
   }
}

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