12.3 Write an application named BadSubscriptCaught in which you declare an array
ID: 3768935 • Letter: 1
Question
12.3 Write an application named BadSubscriptCaught in which you declare an array of 10 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 should also display an error message. Save the file as BadSubscriptCaught.java. Need code HTML/JavaScript to execute and run in Internet Explorer for testing.
Explanation / Answer
import java.util.Scanner;
public class BadSubscriptCaught {
private static Scanner sca;
public static void main(String arg[])
{
sca = new Scanner(System.in);
String[] names={"John","Peter","Mac","Max","Mark","Steve","Thomas","Kit","Barak","Jams"};
System.out.println("Enter the position of Name : ");
int position=sca.nextInt();
try
{
System.out.println(names[position]);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
Enter the position of Name :
12
java.lang.ArrayIndexOutOfBoundsException: 12
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.