gpt4 book ai didi

Java try catch 不处理 IndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-30 03:00:29 25 4
gpt4 key购买 nike

当 try catch Java 中的列表的 IndexOutOfBoundsException 时,我遇到了一些问题。所以我将包含 2 个元素的列表声明为:

List<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));

然后我尝试做一个 try catch:

do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");

try{
option = sc.nextInt();
} catch (IndexOutOfBoundsException e){
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
type = list.get((option - 1));
} while (option <= 0 || option >= 3);

但是,当我输入大于 2 的选项时,它向我抛出 IndexOutOfBounds 异常,但我认为我已经对其进行了 try catch ?

提前致谢。

最佳答案

    do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");

try {
option = sc.nextInt();
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
try {
type = list.get((option - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
option=3;
}
} while (option <= 0 || option >= 3);

我在 type = list.get((option - 1)); 添加了新的 try-catch为了强制用户重新输入选项,我将在捕获原因处将选项设置为 3

关于Java try catch 不处理 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com