如何将星期字符串映射为整数并实现Java星期增减功能?
Java星期计算程序:优化方案与实现
你现在的代码用了大量if语句处理星期的映射和加减,既冗余又不易维护,下面是针对需求的优化方案,重点解决添加天数的分支问题,同时优化整体代码结构。
现有代码
import java.util.Scanner; public class Main { public static void main(String[] args) { Day.userInput(); } } class Day { static int b; public static void userInput() { Scanner scan = new Scanner(System.in); // set day of week System.out.println("Please set the day of the week:"); String day = scan.nextLine(); if(day.equals("sunday") || (day.equals("Sunday")) ) { b = 1; } if(day.equals("monday") || (day.equals("Monday")) ) { b = 2; } if(day.equals("tuesday") || (day.equals("Tuesday")) ) { b = 3; } if(day.equals("wednesday") || (day.equals("Wednesday")) ) { b = 4; } if(day.equals("thursday") || (day.equals("Thursday")) ) { b = 5; } if(day.equals("friday") || (day.equals("Friday")) ) { b = 6; } if(day.equals("saturday") || (day.equals("Saturday")) ) { b = 7; } System.out.println("Enter 1 to return the day.\nEnter 2 to return tomorrows day.\nEnter 3 to return yesterdays day.\nEnter 4 to add days to the current day.\n"); int a = scan.nextInt(); // return day if(a == 1) { System.out.println("The day is " + day); } //return next day if(a == 2) { if ( b == 1) { System.out.println("The next day is Monday."); } if (b == 2) { System.out.println("The next day is Tuesday."); } if (b == 3) { System.out.println("The next day is Wednesday."); } if (b == 4) { System.out.println("The next day is Thursday."); } if (b == 5) { System.out.println("The next day is Friday."); } if (b == 6) { System.out.println("The next day is Saturday."); } if (b == 7) { System.out.println("The next day is Sunday."); } } //return previous day if(a == 3) { if( b == 1) { System.out.println("The previous day was Saturday."); } if (b == 2) { System.out.println("The previous day was Sunday."); } if (b == 3) { System.out.println("The previous day was Monday."); } if (b == 4) { System.out.println("The previous day was Tuesday."); } if (b == 5) { System.out.println("The previous day was Wednesday."); } if (b == 6) { System.out.println("The previous day was Thursday."); } if (b == 7) { System.out.println("The previous day was Friday."); } } // add days if(a == 4 ) { System.out.println("Enter the number of days you want to add"); int c = scan.nextInt(); } } }
核心优化方案
1. 用数组替代if做星期映射
把星期字符串和格式化后的星期名分别存进数组,实现字符串与索引的双向转换,彻底消除大量if判断:
// 小写数组用于匹配用户输入,格式化数组用于输出结果 private static final String[] DAYS_LOWER = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; private static final String[] DAYS_FORMATTED = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
用户输入转小写后,遍历数组就能拿到对应的索引,不用逐个判断大小写。
2. 模运算处理星期循环
星期是7天一个周期,利用模运算直接计算加减后的星期索引,无需分支判断:
- 次日:
(当前索引 + 1) % 7 - 前日:
(当前索引 - 1 + 7) % 7(加7避免索引变为负数) - 添加n天:
(当前索引 + n) % 7,若n为负数,同样加7修正索引确保非负
3. 代码结构优化
- 移除静态变量
b,改用局部变量存储当前星期索引,避免全局副作用 - 将功能拆分为独立方法(如
getDayIndex()负责字符串转索引),代码职责更清晰 - 增加输入合法性校验,处理用户输入无效星期或功能选项的情况,提升程序健壮性
优化后的完整代码
import java.util.Scanner; public class Main { public static void main(String[] args) { DayHandler.handleUserInput(); } } class DayHandler { // 索引对应:0=周日,1=周一,...,6=周六 private static final String[] DAYS_LOWER = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; private static final String[] DAYS_FORMATTED = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; public static void handleUserInput() { Scanner scan = new Scanner(System.in); // 获取并验证用户输入的星期 int currentIndex = -1; while (currentIndex == -1) { System.out.println("Please set the day of the week:"); String inputDay = scan.nextLine().trim().toLowerCase(); currentIndex = getDayIndex(inputDay); if (currentIndex == -1) { System.out.println("Invalid day, please enter a valid day (e.g., Monday, sunday)."); } } // 功能选择循环 while (true) { System.out.println("\nEnter 1 to return the day.\nEnter 2 to return tomorrow's day.\nEnter 3 to return yesterday's day.\nEnter 4 to add days to the current day.\nEnter 0 to exit."); if (!scan.hasNextInt()) { System.out.println("Invalid input, please enter a number between 0-4."); scan.next(); // 清除无效输入 continue; } int choice = scan.nextInt(); switch (choice) { case 0: System.out.println("Exiting program."); scan.close(); return; case 1: System.out.println("The day is " + DAYS_FORMATTED[currentIndex]); break; case 2: int nextIndex = (currentIndex + 1) % 7; System.out.println("The next day is " + DAYS_FORMATTED[nextIndex]); break; case 3: int prevIndex = (currentIndex - 1 + 7) % 7; System.out.println("The previous day was " + DAYS_FORMATTED[prevIndex]); break; case 4: System.out.println("Enter the number of days you want to add (negative numbers subtract days):"); while (!scan.hasNextInt()) { System.out.println("Invalid input, please enter an integer."); scan.next(); } int daysToAdd = scan.nextInt(); int newIndex = (currentIndex + daysToAdd) % 7; // 处理负数取模的异常情况 newIndex = newIndex < 0 ? newIndex + 7 : newIndex; System.out.println("After " + daysToAdd + " days, the day is " + DAYS_FORMATTED[newIndex]); break; default: System.out.println("Invalid choice, please enter a number between 0-4."); } } } // 根据小写星期字符串获取对应索引 private static int getDayIndex(String dayLower) { for (int i = 0; i < DAYS_LOWER.length; i++) { if (DAYS_LOWER[i].equals(dayLower)) { return i; } } return -1; // 未找到返回-1表示输入无效 } }
关键优化点说明
- 数组映射:彻底消除大量if判断,代码更简洁易维护,后续新增或修改星期只需调整数组即可
- 模运算:利用星期的周期性,用数学计算替代分支判断,逻辑清晰且高效
- 输入校验:避免因无效输入导致程序崩溃,提升用户体验
- 结构拆分:代码职责明确,可读性和可维护性大幅提升
内容的提问来源于stack exchange,提问作者Leek
相关产品推荐
相关产品推荐

