189k views
2 votes
Write an application in which you declare an array of eight first names. Write a try block in which you prompt the user for an integer and display the name in the requested position. Create a catch block that catches the potential ArrayIndexOutOfBoundsException thrown when the user enters a number that is out of range. The catch block also should display the error message Subscript out of range.

1 Answer

6 votes

Answer:

import java.util.*;

public class Main

{

public static void main(String[] args) {

String[] names = {"Ted", "Marshall","Lily", "Barney","Robin", "Stella", "Ranjit", "Wendy"};

Scanner input= new Scanner(System.in);

int i;

try

{

System.out.print("Enter an integer(1 to 8) to display a name in that position: ");

i = input.nextInt();

i = i - 1;

System.out.println(names[i]);

input.close();

}

catch (ArrayIndexOutOfBoundsException e){

System.out.println("Number is out of range!");

}

}

}

Step-by-step explanation:

Initialize an array containing 8 names

Inside the try block:

Ask the user for a number

Decrease the number by 1, so that it corresponds to the array index

Print the name in that position

Inside the catch block, define an ArrayIndexOutOfBoundsException that will print the error message, if the user enters a number that is not in the range

User Dan Smart
by
5.2k points