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

1 Answer

7 votes

Step-by-step explanation:

try{

String[] names={"Tom","Suzie","Lina","Harry","Rosy"};

Scanner input=new Scanner(System.in);

System.out.println("Enter an integer: ");

int position=input.nextInt();

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

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Subscript out of range.");

}

User Joshua Conner
by
7.5k points

Related questions