任务描述:
定义并初始化一个包含10个整型元素的数组;
定义一个search(int[] arr, int x)方法,根据索引号x在数组中找出下标为x的数组元素,并返回该元素的值。
从键盘输入一个索引号,调用search方法,输出索引号对应的数组元素的值。
捕捉并处理输入索引号类型不匹配异常( InputMismatchException )和数组下标越界异常(ArrayIndexOutOfBoundsException)。
public class Exception{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int [] a= {23,56,789,-12,35,67,89,75,66,32};
int x;
try {
x=scan.nextInt();
System.out.println("查找到的元素是:"+search(a,x));
}catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("输入的索引号越界"+e1.getMessage());
}catch (InputMismatchException e2) {
System.out.println("输入数据类型不匹配"+e2.getMessage());
}
}
public static int search(int [] a,int x) {
return a[x];
}
}