2011-12-04 30 views
0

我不希望由於不返回任何內容而擱淺用戶。通常我可以使用簡單的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循環將繼續循環,直到學生數組中的所有元素均已通過爲止,所以我不會期望獲得不準確的輸出。有什麼建議?

+1

嘗試使用方法和返回的東西,而不是僅僅打印到控制檯。這使您可以更好地控制程序的流程。 –

+0

你能否包括學生宣言? – hmjd

回答

1

提取您的for循環進入一個方法,返回你所感興趣的模塊。

然後調用該方法。檢查你是否得到有用的結果,並打印或打印你的藉口。

這被稱爲關注的分離。一個實體應該只做一件事。你的for循環做至少有三個:

  • 尋找學生
  • 搜索模塊
  • 打印效果
2

您可以添加一個簡單的標記值(布爾標誌),以您的while語句。您將該值作爲false開始,然後在找到記錄時將其更改爲true。

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; 
        } 

或者您可以使用「break」語句來終止循環。

while (it.hasNext()) { 
       Module module = (Module) it.next(); 
       if (module.getStudents().contains(student)) { 
          System.out.printf("%s ", module.getName()); 
          break; 
        } 
+0

@ Boundless您的第一個選項看起來應該可以工作,但我仍然返回與以前相同的結果。我已編輯帖子以顯示這些更改。 – newToJava

+0

@MikeGittins確保將支票添加到第二個打印語句中:否則如果(!發現){0} – Boundless