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