原题目:
附加要求:
除了满足题目的要求,另外结合异常机制完成如下额外要求:
(a) 允许用户持续输入下标值,显示对应的元素值,直到用户输入-1退出程序;
(b) 如果出现用户输入的下标越界,提示用户后,还允许用户继续输入正确的值
(注意要排除越界值为-1的情况,要求通过构建自定义异常的方式来解决该任务)。
做作业的时候,实在是想不到应该怎样自定义异常,就没有使用,直接用了if语句进行控制。代码如下:
import java.util.Scanner;
public class Exercise12_03 {
public static void main(String[] args) {
int[] array = getRandomArray();
while (true) {
System.out.print("Enter the index: ");
Scanner input = new Scanner(System.in);
int i = input.nextInt();
try {
System.out.println(getValue(i, array));
} catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println(ex1.getMessage());
}
finally {
if(i == -1)
break;
}
}
}
// 生成随机数组
public static int[] getRandomArray() {
int[] randomArray = new int[100];
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int)(Math.random()*100);
}
return randomArray;
}
// 根据给定索引,从数组中获取数值
public static int getValue(int n, int[] array) throws ArrayIndexOutOfBoundsException {
if (n >= 0 && n <100)
return array[n];
else
throw new ArrayIndexOutOfBoundsException("Out of Bounds");
}
}
对参考代码研究之后发现,其使用的自定义异常只是在原基础上增加了index属性。这一点我在最初做的时候也有想到,但是因为觉得不可能这么简单,试图在自定义异常类里实现选择操作,把问题复杂化之后反而无法解决了。归根到底,还是自己对自定义异常的使用没有理解透彻。
结合参考代码的修改结果如下:
import java.util.Scanner;
public class Exercise12_03 {
public static void main(String[] args) {
int[] array = getRandomArray();
while (true) {
System.out.print("Enter the index: ");
Scanner input = new Scanner(System.in);
int i = input.nextInt();
try {
System.out.println(getValue(i, array));
} catch (CustomArrayIndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
if(ex.getIndex() == -1)
break;
}
}
}
// 生成随机数组
public static int[] getRandomArray() {
int[] randomArray = new int[100];
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int)(Math.random()*100);
}
return randomArray;
}
// 根据给定索引,从数组中获取数值
public static int getValue(int n, int[] array) throws CustomArrayIndexOutOfBoundsException {
if (n >= 0 && n <100)
return array[n];
else
throw new CustomArrayIndexOutOfBoundsException(n, "Out of Bounds");
}
}
class CustomArrayIndexOutOfBoundsException extends Exception {
private int index;
// constructors
public CustomArrayIndexOutOfBoundsException() {
}
public CustomArrayIndexOutOfBoundsException(int index, String message) {
super(message);
this.index = index;
}
// accessor
public int getIndex() {
return index;
}
}