幾個(gè)月前我開始研究 Java,現(xiàn)在我陷入了異常處理中,我需要的是,每個(gè)StudentId、TeamID 都必須拋出一輪異常檢查,以便如果用戶輸入字母而不是整數(shù),它應(yīng)該發(fā)送回在同一個(gè)地方再次詢問那個(gè)值。我正在使用 ArrayList 來存儲(chǔ)數(shù)據(jù)。此外,所有g(shù)et************() 方法都在另一個(gè)名為Student 的類中。studentList是我訪問我的ArrayList 的變量請(qǐng)通過修復(fù)它來幫助我找到我的錯(cuò)誤在哪里,以便我的概念更加清晰。我被困在這里/*** * 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貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
我將通過使用 while 循環(huán)給您另一個(gè)提示,您可以根據(jù)您的要求進(jìn)一步實(shí)現(xiàn)此邏輯。您可以在致電之前使用它c(diǎn)heckStudent()
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貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
添加回答
舉報(bào)
0/150
提交
取消