我不知道这段代码有什么问题。当我输入匹配的正确的nomatric
时,它将显示正确的,但也会显示错误消息。
怎么了?
public void Search(int nomatric) {
for (int i = 0; i < student.length; i++) {
if (student[i].matrix == nomatric) {
System.out.printf("%-25s%-25s%-25s%-25s%-25sn", "Matric", "Name", "Course work", "Final exam", "Grade");
System.out.printf("%-20d %-20s %-20.2f %-20.2f %-20s", student[i].matrix, student[i].name, student[i].coursework, student[i].finalexam, student[i].grade);
System.out.println();
}
}
System.out.println("Cannot find the matric number!!!");
System.out.println();
}
使用一个标志变量。在for循环之前将其设置为false。在循环中,只要找到匹配,就将此标志设置为true。在循环外对标志使用if条件。如果flag为false表示没有找到匹配,则只打印错误。
public void Search(int nomatric) {
boolean flag=false;
for (int i = 0; i < student.length; i++) {
if (student[i].matrix == nomatric) {
System.out.printf("%-25s%-25s%-25s%-25s%-25sn", "Matric", "Name", "Course work", "Final exam", "Grade");
System.out.printf("%-20d %-20s %-20.2f %-20.2f %-20s", student[i].matrix, student[i].name, student[i].coursework, student[i].finalexam, student[i].grade);
System.out.println();
flag=true;
}
}
if( ! flag) {
System.out.println("Cannot find the matric number!!!");
System.out.println();
}
}
您的错误消息System.out.println("Cannot find the matric number!!!");
在代码中是无条件的,因此它将始终显示该错误
您返回void
,因此您无法获得早期有意义的return
块的便利。您确实需要表明您已以某种方式进入if
块。你有两个*选项:
- 使用布尔值表示,如果您已经输入了
if
块,那么您不应该打印消息,或者 - 从方法返回
String
而不是隐式打印它,并让调用者打印返回消息。
(*:您还可以从if语句中选择return
,尽管不推荐使用这种样式。这意味着,您可以将return
紧接在System.out.println()
之后,而不是使用boolean
变量。
public void search(int nomatric) {
boolean success = false;
for (int i = 0; i < student.length; i++) {
if (student[i].matrix == nomatric) {
success = true;
System.out.printf("%-25s%-25s%-25s%-25s%-25sn", "Matric", "Name", "Course work", "Final exam", "Grade");
System.out.printf("%-20d %-20s %-20.2f %-20.2f %-20s", student[i].matrix, student[i].name, student[i].coursework, student[i].finalexam, student[i].grade);
System.out.println();
}
}
if(!success) {
System.out.println("Cannot find the matric number!!!");
System.out.println();
}
}