import java.util.Scanner; public class Calendar2023 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] calendar = generateCalendar();

    // 获取用户输入的月份 
    System.out.print("请输入一个月份(1-12): "); 
    int month = scanner.nextInt(); 
    
    // 打印指定月份的日历 
    printCalendar(calendar, month); 
    
    scanner.close(); 
} 

// 生成2023年的日历数组 
public static int[] generateCalendar() { 
    int[] calendar = new int[365]; 
    int dayOfWeek = 2; // 2023年1月1日是星期日,对应数组索引为2 
    
    for (int i = 0; i < calendar.length; i++) { 
        calendar[i] = dayOfWeek; 
        
        // 计算下一天的星期几 
        dayOfWeek = (dayOfWeek + 1) % 7; 
    } 
    
    return calendar; 
} 

// 打印指定月份的日历 
public static void printCalendar(int[] calendar, int month) { 
    if (month < 1 || month > 12) { 
        System.out.println("无效的月份!"); 
        return; 
    } 
    
    // 打印月份标题 
    System.out.println("2023年" + month + "月的日历:"); 
    System.out.println("日	一	二	三	四	五	六"); 
    
    // 计算指定月份的起始位置 
    int startIndex = 0; 
    for (int i = 1; i < month; i++) { 
        startIndex += getDaysOfMonth(i); 
    } 
    
    // 计算指定月份的天数 
    int daysOfMonth = getDaysOfMonth(month); 
    
    // 打印日历内容 
    for (int i = 0; i < startIndex; i++) { 
        System.out.print(calendar[i] + "\t"); 
    } 
    for (int i = 1; i <= daysOfMonth; i++) { 
        System.out.print(i + "\t"); 
        if ((startIndex + i) % 7 == 0) { 
            System.out.println(); 
        } 
    } 
    System.out.println(); 
} 

// 获取指定月份的天数 
public static int getDaysOfMonth(int month) { 
    int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
    return daysOfMonth[month - 1]; 
} 

}


原文地址: https://www.cveoy.top/t/topic/pZ44 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录