好的,所以我的问题是关于 boolean 值返回。对于我的 Comp Sci 作业,我必须使用方法制作类(class)注册程序,其中之一是添加类(class)方法。基本上,您在目录中搜索类(class),如果匹配,则将其添加到学生的日程安排中并返回 boolean 值 true。我这样做了,但出于某种原因,它给了我一个错误。这是代码:
public static boolean addCourse(
Course[] catalog,
Course[] mySchedule,
int myNumCourses,
int dept,
int courseNum)
{
int j;
int i;
int k;
int deptCat;
int courseNumCat;
Course courseAdd = null;
char checkDay;
int checkTime;
if (mySchedule.length == myNumCourses) {
return false;
}
for (i = 0 ; i < catalog.length ; i++) {
Course course = catalog[i];
deptCat = course.getDepartment();
courseNumCat = course.getCourseNumber();
if (deptCat == dept && courseNumCat == courseNum) {
courseAdd = catalog[i];
break;
}
else continue; }
for (j = 0 ; j < myNumCourses ; j++) {
if (mySchedule[j] == null) {
mySchedule[j] = courseAdd;
return true;
}
else continue;
}
for (k = 0 ; k < mySchedule.length ; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay() && checkTime == courseAdd.getPeriod()) {
return false;
}
}
else continue;
}
}
为什么它不能识别 boolean 返回值?是因为我把它们放在了一个循环中吗?
最佳答案
您需要在您的方法末尾放置一个return
语句,即使您可能知道它永远不会到达(编译器不够智能,无法知道这一点,这就解释了错误)。
例如,即使这样也不会编译:
public static boolean foo() {
if (true)
return true;
}
除非我们添加最后一个 return
语句。你所拥有的是类似的。
关于java - 返回 boolean 值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390982/