我正在为我的学校制作一个项目,我已处理所有异常,但我无法处理ArrayOutOfBoundsException。 所以我在stackoverflow上搜索了一个解决方案,它说要使用IndexOutOfBoundsException(链接到解决方案:why is it not catching the arrays out of bound?) 但它没有用。请帮忙? 这是我的代码:
for (int i = 0; i < 4; i++) {
System.out.println(fruit[i] + fruitprice[i]);
}
System.out.println("\n" + "please enter the number marked for the icecream you want to buy");
do {
x = 0;
try {
icenum1 = Integer.parseInt( in .readLine()) - 1;
} catch (NumberFormatException n) {
System.out.println("please enter in numbers and not in words.... please try again");
x = 1;
} catch (IndexOutOfBoundsException e) {
System.out.println("please enter a number out of the given numbers and not any other number");
x = 1;
}
} while (x != 0);
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
答案 0 :(得分:0)
如果它仍然尊重代码的逻辑,则将这些行移动到try块中。
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
如果抛出IndexOutOfBoundException
,它将来自第二行,因为它将尝试访问当前数组中不存在的索引。