java - 异常java后继续代码
问题描述
我想在索引是已经指定的索引的数组中输入学生数据。所以,我使用 try、catch 和 loop 来输入学生,但是当用户输入的数据超过索引时,我希望程序让他们停止输入但结果会被打印出来。例如:
import java.util.Scanner;
String[] students = new String[5];
String answer = "";
try {
do {
//my code to input the students
}
while(answer.equalsIgnoreCase("Y"))
//output the students
}
catch(ArrayIndexOutOfBoundsException ex)
{
//the code that let the code continue or print the data from above
}
我应该使用 finally 来打印输出还是可以在上面添加一些东西?
解决方案
你应该颠倒你的顺序try catch
和loop
:
import java.util.Scanner;
String[] students = new String[5];
String answer = "";
do {
try {
//my code to input the students
} catch(ArrayIndexOutOfBoundsException ex)
{
//the code that let the code continue or print the data from above
}
}
while(answer.equalsIgnoreCase("Y"))
//output the students
编辑:这与 Shanu Gupta 的答案相同
推荐阅读
- python - Django/Parler:无法在 update_or_create 函数中访问模型的翻译字段
- react-native - React Native Permissions“未检测到权限处理程序”
- c# - Blazor WASM 无法调试 GetAuthenticationStateAsync
- python - 制作 Python 比较列表
- python - 如果不存在,Python会创建一个文件夹列表
- java - 如何在片段中找到主机活动的按钮ID并将数据发送到片段中的主机活动
- java - 谷歌 ARCore Sceneform 如何检测光线击中 ar 对象
- python - 自信地点击图像python
- php - 在 wordpress 滑块中向图像添加替代文本
- c++ - 不知道对齐的数组形式分配函数的标准库版本是否满足对齐要求?