Java中Calendar.set方法无法修改Calendar变量问题求助
Ugh, I feel your pain with Java’s old Calendar class—it’s loaded with gotchas that can make you want to slam your laptop shut. Let’s break down the issues I spot in your snippet and fix them step by step:
Key Problems & Fixes
Static
CalendarInstance Risks
Ifcalis a static variable, every call tocalendarGet()will modify the same instance, leading to leftover state from previous runs (e.g., a year set last time bleeding into the current call). Instead, create a fresh instance each time to avoid unexpected behavior:Calendar cal = Calendar.getInstance(); // Fresh, clean instance every timeMonth Index Confusion
You’re subtracting 1 fromMONTH, which is correct becauseCalendar.MONTHis zero-indexed (January = 0, December = 11). But double-check that yourMDFromDate(md)method is parsing the input month as a 1-based integer (e.g., "05" becomes 5, so5-1 = 4which is May). IfMDFromDatealready returns a zero-based value, you’ll end up with the wrong month.Missing Input Validation
Your code grabs the input and finds the slash, but doesn’t check if the input is valid (e.g., no slash, non-numeric values, or impossible dates like 13/32). Adding validation will prevent runtime crashes:int slash = md.indexOf('/'); if (slash == -1) { System.out.println("Invalid format! Use mm/dd."); return; } try { int inputMonth = Integer.parseInt(md.substring(0, slash)); int inputDay = Integer.parseInt(md.substring(slash + 1)); // Add checks: inputMonth 1-12, inputDay 1-31 (then verify against actual month max) } catch (NumberFormatException e) { System.out.println("Date must contain numbers!"); return; }Calculating
MAX_DAYProperly
Assuming you’re trying to get the number of days in the target month, once you’ve set the calendar to the correct month and year, use this to account for leap years and varying month lengths:MAX_DAY = cal.getActualMaximum(Calendar.DATE);
Pro Tip: Ditch Calendar for Java 8+ java.time
If you’re using Java 8 or later, the java.time API is way more intuitive and avoids all the Calendar headaches. Here’s how you could rewrite this logic cleanly:
public static void calendarGet() { String md = getInput("What date would you like to look at?(mm/dd)"); try { MonthDay monthDay = MonthDay.parse(md, DateTimeFormatter.ofPattern("MM/dd")); LocalDate targetDate = monthDay.atYear(Year.now().getValue()); int targetDay = targetDate.getDayOfMonth(); int maxDay = targetDate.lengthOfMonth(); // Rest of your logic here } catch (DateTimeParseException e) { System.out.println("Invalid date format! Use mm/dd."); } }
No zero-based months, no mutable state, and built-in validation—total game-changer.
内容的提问来源于stack exchange,提问作者Cyrus Bozorgzad

