gpt4 book ai didi

java - 捕获错误后如何正确循环?

转载 作者:行者123 更新时间:2023-11-30 07:08:55 24 4
gpt4 key购买 nike

我正在进行我的数据库项目。包含以下类:

主要

StudentCollection

学生

在我的 StudentCollection 类中,我有以下方法/查询:

public Students getStudentForIndex(int index){
try {
return list.get(index);
}catch(InputMismatchException e){
System.out.println("Incorrect character entered");
return null;
}
}

我想就如何解决该方法的循环问题征求您的建议。

原因 - 如果用户输入错误,我想警告用户该错误并要求他再次输入,不断捕获可能抛出的错误

最佳答案

boolean finished = false;
Student s;

while (!finished) {
s = getStudentForIndex(getInput());
if (s != null)
finished = true;
}

// Do stuff with the Student s here.

循环将循环直到 finished 为真。这会获取输入并将其传递给 getStudentForIndex 方法。如果该输入导致 InputMismatchException,则 s 将为空。如果 s 不为空,那么你就完成了,完成可以为真。

关于java - 捕获错误后如何正确循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23698441/

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