使用Java中的if语句创建用户友好的界面

时间:2011-12-04 12:56:10

标签: java

我不希望通过返回任何内容而使用户陷入困境。通常我可以使用一个简单的if else语句来纠正这个问题,但由于它嵌套在for循环中,我得不到很好的结果。以下是关于返回模块的学生的代码:

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

显然,在这个例子中,Jane确实存在于数据库中,并且她在UFCE3和UFCE1上注册。

由于if语句嵌套在for循环中,因此for循环将继续循环直到学生数组中的所有元素都被传递,因此我不会期望得到任何不准确的输出。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您可以在while语句中添加一个简单的sentinel值(布尔标志)。您将值关闭为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;
                  }

答案 1 :(得分:1)

将你的for循环解压缩到一个方法中,返回你感兴趣的模块。

然后调用该方法。检查你是否得到任何有用的结果并打印出来或打印你的借口。

这被称为关注点。一个实体应该只做一个thig。你的for循环至少有三个:

  • 寻找学生
  • 搜索模块
  • 打印结果