使用 ArrayList 和 java 进行异常处理



几个月前我开始研究java,现在我被困在异常处理中,我需要的是,每个StudentId,TeamID都必须抛出一轮异常检查,以便如果用户输入字母代替整数,它应该发送回同一位置再次询问该值。我正在使用ArrayList来存储数据。此外,所有 get**********(( 方法都在另一个名为Student的类中。学生列表是我访问我的数组列表的变量

请帮助我通过修复它找到我的错误在哪里,以便我的概念更加清晰。我被困在这里

/***
* 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("*******************************************");   
}
}  

我会通过使用 while-loop 给你另一个提示,你可以根据你的要求进一步实现这个逻辑。您可以在调用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
}
}

请阅读 Java 语言规范中的try..catch语句或任何教程(您可以通过在您喜欢的搜索引擎中键入"java try catch"来找到许多教程(。

我相信你能弄清楚。

最新更新