需求:每週一、二、五上課 (每週 3 堂),共 50 堂課,從今天起算,求結束日期。
Calendar.DAY_OF_WEEK,1=週日...7=週六)。Calendar.add(DAY_OF_MONTH, totalDays) 得出結束日期。
import java.util.Calendar;
public class CourseEndDateCalculator {
static final int CLASSES_PER_WEEK = 3; // 週一、二、五
static final int TOTAL_CLASSES = 50;
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_WEEK); // 1~7
// 1. 本週剩餘上課數
int classesThisWeek = 0;
if (today == Calendar.MONDAY || today == Calendar.TUESDAY) classesThisWeek = 3; // 週一、二本週還有3堂
else if (today == Calendar.WEDNESDAY || today == Calendar.THURSDAY) classesThisWeek = 1; // 只剩週五
else if (today == Calendar.FRIDAY) classesThisWeek = 1;
else classesThisWeek = 0; // 週六、日
// 2. 本週剩餘自然天數 (到週六)
int daysToSaturday = (Calendar.SATURDAY - today + 7) % 7;
if (daysToSaturday == 0) daysToSaturday = 7; // 今天是週六
// 3. 扣除本週後剩餘課數
int remaining = TOTAL_CLASSES - classesThisWeek;
if (remaining <= 0) { // 本週上完
// 邏輯略:直接根據今天往後推
}
int fullWeeks = remaining / CLASSES_PER_WEEK;
int extraClasses = remaining % CLASSES_PER_WEEK;
// 4. 額外課數對應偏移天數 (從週日開始算)
int extraDays = 0;
switch (extraClasses) {
case 0: extraDays = -1; break; // 正好結束上週五
case 1: extraDays = 2; break; // 週一
case 2: extraDays = 3; break; // 週一、二
case 3: extraDays = 6; break; // 週一、二、五
}
int totalDays = daysToSaturday + fullWeeks * 7 + extraDays;
cal.add(Calendar.DAY_OF_MONTH, totalDays);
System.out.printf("跨度 %d 天,結束日期:%tF 星期 %d%n",
totalDays, cal, cal.get(Calendar.DAY_OF_WEEK));
}
}
import java.time.*;
import java.time.temporal.TemporalAdjusters;
public class ModernCalculator {
public static void main(String[] args) {
LocalDate start = LocalDate.now();
long classes = 50;
long weeks = classes / 3;
int extra = (int)(classes % 3);
LocalDate end = start.plusWeeks(weeks);
// 從 end 往後找第 extra 個上課日 (週一、二、五)
// 略...
}
}
java.time API 更清晰、不可變、執行緒安全,強烈建議新專案使用。