基于当前日期时间,如何从Cell数组中查找学生的下一节课?
解决寻找下一节课的逻辑问题
看起来你已经搞定了当前日期和小时的获取,核心问题就是怎么准确筛选出当前时间之后的最早课程。我来帮你把这段代码的逻辑补全:
首先得明确判断「下一节课」的规则:
- 课程的
day大于当前currentDay:这肯定是未来的课,需要纳入候选 - 课程的
day等于currentDay但startTime大于currentHour:这是今天还没上的课,也得算候选 - 其他情况(day更小,或者day相同但startTime更早):都是已经上完的课,直接跳过
接下来要在所有符合条件的候选里,挑出最早的那一个——先比day,day小的更早;如果day相同,就比startTime,数值小的更早。
下面是修改后的完整代码:
public Cell getNextClass(int studentID, Context context){ DBHelper dbHelper = new DBHelper(context); Cell[] cell = dbHelper.queryCellData(studentID); Date currentTime = Calendar.getInstance().getTime(); int currentDay = getCurrentDay(currentTime.toString()); Log.d(TAG, "currentDay: " + currentDay); DateFormat dateFormat = new SimpleDateFormat("hh a"); String formattedDate= dateFormat.format(currentTime); int currentHour = getCurrentHour(formattedDate); Cell nextClass = null; // 初始化为null,避免默认值干扰判断 // 用增强for循环遍历,代码更简洁易读 for (Cell currentCell : cell) { int cellDay = currentCell.getDay(); int cellStartTime = currentCell.getStartTime(); // 判断当前课程是否在未来 boolean isFutureClass = false; if (cellDay > currentDay) { isFutureClass = true; } else if (cellDay == currentDay && cellStartTime > currentHour) { isFutureClass = true; } if (isFutureClass) { // 还没找到候选的话,直接把当前课程设为下一节课 if (nextClass == null) { nextClass = currentCell; } else { // 对比当前候选和新找到的课程,保留更早的那个 boolean isEarlier = false; if (cellDay < nextClass.getDay()) { isEarlier = true; } else if (cellDay == nextClass.getDay() && cellStartTime < nextClass.getStartTime()) { isEarlier = true; } if (isEarlier) { nextClass = currentCell; } } } } // 处理边界情况:如果所有课程都在当前时间之前,返回下一周的最早课程(可根据需求调整) if (nextClass == null) { nextClass = cell[0]; for (Cell currentCell : cell) { boolean isEarlier = false; if (currentCell.getDay() < nextClass.getDay()) { isEarlier = true; } else if (currentCell.getDay() == nextClass.getDay() && currentCell.getStartTime() < nextClass.getStartTime()) { isEarlier = true; } if (isEarlier) { nextClass = currentCell; } } Log.d(TAG, "All classes are in the past, returning next week's first class"); } return nextClass; }
关键逻辑说明:
- 初始化
nextClass为null:避免一开始就把cell[0]作为默认值(比如你测试场景里cell[0]是day=1的课,已经过了) - 增强for循环:比普通for循环更直观,遍历每个Cell元素
- 未来课程判断:分两种场景覆盖所有未上课的情况
- 筛选最早课程:每次找到符合条件的课程,都和当前候选对比,确保留下的是最早的
- 边界处理:如果所有课程都已过期,默认返回下一周的最早课程(你可以改成返回null或者其他提示逻辑)
用你给出的测试场景(currentDay=2、currentHour=21,数组里有day=1、startTime=12和day=3、startTime=8的课程),这段代码会正确返回day=3的课程。
内容的提问来源于stack exchange,提问作者DigitalJesus
相关产品推荐
相关产品推荐

