2011-12-04 32 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