几个月前我开始研究 Java,现在我陷入了异常处理中,我需要的是,每个StudentId、TeamID 都必须抛出一轮异常检查,以便如果用户输入字母而不是整数,它应该发送回在同一个地方再次询问那个值。我正在使用 ArrayList 来存储数据。此外,所有get************() 方法都在另一个名为Student 的类中。studentList是我访问我的ArrayList 的变量请通过修复它来帮助我找到我的错误在哪里,以便我的概念更加清晰。我被困在这里/*** * A method to check if the same Student ID exists in the ArrayList previously * @param StudentId * @return */public static boolean checkStudent(int StudentId) { for (Student stud : studentList) { if(stud.getStudentId() == StudentId) { return true; } } return false;}/*** * Method to add student in the ArrayList * @param scn */public static void addStudent(Scanner scn) { System.out.println("Enter student ID"); int studentId; studentId = scn.nextInt(); **//enter the try catch statement here //ask the user to write the integer not string and revert to this scanner variable** if (checkStudent(studentId)) { System.out.println("Student Id " + studentId + " already exists,Please enter the valid details "); addStudent(scn); //break; }else{ System.out.println("Enter student name:"); String studentName; studentName = scn.next(); System.out.println("Enter team ID:"); **try{ int teamId; teamId = scn.nextInt(); //ask the user to write the integer not string and revert to this scanner variable }catch(NumberFormatException e){ // }finally{ //do something }** System.out.println("Enter team name:"); String teamName;try{ teamName = scn.next(); } Student std = new Student(studentId, studentName, teamId, teamName); studentList.add(std); System.out.println("*******************************************"); System.out.println("student with Student ID" + studentId +" added succesfully"); System.out.println("*******************************************"); }}
2 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
我将通过使用 while 循环给您另一个提示,您可以根据您的要求进一步实现此逻辑。您可以在致电之前使用它checkStudent()
System.out.println("Enter student ID");
while (true) {
try {
int studId= scn.nextInt();
// terminate loop if everything is ok
break;
} catch (NumberFormatException e) {
// on an exception, loop still continues
}
}
呼如林
TA贡献1798条经验 获得超3个赞
添加回答
举报
0/150
提交
取消