我正在编写一个程序,用于在ArrayList中存储约会。要求用户键入约会的日期,开始时间和结束时间。程序需要在用户想要提交新约会时检查是否已经有约会。这是递归二进制搜索部分。这是我到目前为止实施的内容。
方法:
public boolean overlap(ArrayList<Appointment> list, int start, int end,
Calendar startCal, Calendar endCal)
{
int middle = (start + end)/2;
System.out.println("Start: " + start + " End: " + end + " Middle: " + middle);
Appointment appt = list.get(middle);
if(start == end){
return((startCal.compareTo(appt.getStart()) >= 0 && startCal.compareTo(appt.getEnd()) <= 0 ) ||
endCal.compareTo(appt.getEnd()) <= 0 && endCal.compareTo(appt.getStart()) >= 0 );
}
else if(startCal.compareTo(appt.getStart()) <= 0 && endCal.compareTo(appt.getStart()) <= 0){
return overlap(list, start, middle - 1, startCal, endCal);
}
else{
return overlap(list, middle, end, startCal, endCal);
}
}
我如何称呼它:
case 1 : //Enter a new appointment
setCal();
startDate = new GregorianCalendar(year, month, day, hour, minute);
endDate = new GregorianCalendar(year, month, day, endHour, endMinute);
appt = new Appointment(description, startDate, endDate);
if(apptList.isEmpty()){
apptList.add(appt);
}
else{
boolean isOverlap = overlap(apptList, 0, apptList.size() - 1,
appt.getStart(), appt.getEnd());
if(isOverlap){
System.out.println("");
System.out.println("ERROR: There is already an appointment at that time");
System.out.println("");
}
else{
int indexToBeAdded = indexFinder(apptList, 0, apptList.size() -1,
appt.getStart(), appt.getEnd());
Appointment tmp = apptList.get(indexToBeAdded);
if(tmp.start.compareTo(appt.start) < 0){
apptList.add(indexToBeAdded + 1, appt);
}
else{
apptList.add(indexToBeAdded , appt);
}
}
}
choice = 0;
break;
setCal()只是提示用户输入所有日历参数,并根据输入的内容设置它们。另外,indexFinder是另一种递归二进制搜索方法,它找到应该添加约会的索引,以便添加约会正确的订单。
截至目前,在我第三次约会时,我尝试添加一个堆栈溢出异常。
感谢您的帮助
答案 0 :(得分:0)
return overlap(list, start, middle - 1, startCal, endCal);
如果你用start = 0和end = 1调用重叠,中间= 0 + 1/2 = 0,那么你用start = 0和end = -1调用重叠...这意味着它们会进一步飞行进一步分开,你跳过了start == end
的停止条件。
尝试将start == end
转为start > end
。
编辑:问题二是这个电话
return overlap(list, middle, end, startCal, endCal);
如果用start = 0和end = 1调用重叠,中间= 0 + 1/2 = 0,那么你用start = 0和end = 1调用重叠...无限递归循环!堆栈溢出!它永远不会结束。
要解决此问题,请将middle
转换为middle + 1
。