2025.3.18(周二)
计算星期的代码:
package day; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Day { public static int which_week(int y, int m, int d) { int w = ((d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7) + 1; return w; } public static void main(String[] args) { // 创建主窗口 JFrame frame = new JFrame("日期计算星期"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); // 创建标签和输入框 JLabel labelYear = new JLabel("请输入年份:"); labelYear.setBounds(50, 30, 100, 25); frame.add(labelYear); JTextField textYear = new JTextField(); textYear.setBounds(150, 30, 150, 25); frame.add(textYear); JLabel labelMonth = new JLabel("请输入月份:"); labelMonth.setBounds(50, 70, 100, 25); frame.add(labelMonth); JTextField textMonth = new JTextField(); textMonth.setBounds(150, 70, 150, 25); frame.add(textMonth); JLabel labelDay = new JLabel("请输入日期:"); labelDay.setBounds(50, 110, 100, 25); frame.add(labelDay); JTextField textDay = new JTextField(); textDay.setBounds(150, 110, 150, 25); frame.add(textDay); // 结果显示 JLabel resultLabel = new JLabel(""); resultLabel.setBounds(50, 200, 300, 25); frame.add(resultLabel); // 创建按钮 JButton button = new JButton("计算星期"); button.setBounds(150, 150, 120, 30); frame.add(button); // 按钮点击事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { int year = Integer.parseInt(textYear.getText()); int month = Integer.parseInt(textMonth.getText()); int day = Integer.parseInt(textDay.getText()); if (!isValidDate(year, month, day)) { resultLabel.setText("输入日期无效,请重新输入!"); return; } int week = which_week(year, month, day); String[] weekNames = {"", "一", "二", "三", "四", "五", "六", "日"}; resultLabel.setText("星期" + weekNames[week]); } catch (NumberFormatException ex) { resultLabel.setText("请输入有效的数字!"); } } }); // 显示窗口 frame.setVisible(true); } // 验证日期是否有效 public static boolean isValidDate(int year, int month, int day) { if (year < 1900 || year > 2050) { return false; } if (month < 1 || month > 12) { return false; } if (day < 1 || day > 31) { return false; } if (month == 2) { if (isLeapYear(year) && day > 29) { return false; } if (!isLeapYear(year) && day > 28) { return false; } } if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) { return false; } return true; } // 判断是否是闰年 public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } }