我不希望由于不返回任何内容而搁浅用户。通常我可以使用简单的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