我不希望由於不返回任何內容而擱淺用戶。通常我可以使用簡單的if語句糾正這個問題,但是因爲它嵌套在for循環中,所以我得不到很好的結果。下面是我返回連接到模塊學生代碼:在Java中使用if語句創建用戶友好的界面
System.out.print("Search for a student: ");
scan = new Scanner(System.in);
String searchStudent = scan.nextLine().trim();
for (Student student : students) {
if (searchStudent.equalsIgnoreCase(student.getName())) {
Iterator it = modules.iterator();
Boolean found = false;
while (it.hasNext() && !found) {
Module module = (Module) it.next();
if (module.getStudents().contains(student)) {
System.out.printf("%s ", module.getName());
found = true;
}
}
} else {
System.out.println("Sorry. " + searchStudent + " does not exist in the database");
}
}
輸出:
Search for a student: jane
UFCE3 UFCE1 Sorry. jane does not exist in the database
Sorry. jane does not exist in the database
Sorry. jane does not exist in the database
Sorry. jane does not exist in the database
顯然,在這個例子中,簡確實存在於數據庫中,她被登記在UFCE3和UFCE1。
由於if語句嵌套在for循環中,因此for循環將繼續循環,直到學生數組中的所有元素均已通過爲止,所以我不會期望獲得不準確的輸出。有什麼建議?
嘗試使用方法和返回的東西,而不是僅僅打印到控制檯。這使您可以更好地控制程序的流程。 –
你能否包括學生宣言? – hmjd