几个月前我开始研究 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("*******************************************");
}
}
白猪掌柜的
呼如林
相关分类