几个月前,我开始研究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("*******************************************");
}
}
答案 0 :(得分:2)
我将使用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
}
}
答案 1 :(得分:1)
请阅读try..catch
statement in the Java language specification或任何教程(您可以通过在您喜欢的搜索引擎中键入“ java try catch”来找到许多内容)。
我确定你能弄清楚。