java控制台输出万年历
用java实现简单的万年历输出的代码
package clock;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class Lunar {private int year;private int month;private int day;private boolean leap;final static String chineseNumber[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};static SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd 日");final static long[] lunarInfo = new long[]{0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520,0x0dd45,0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0};//====== 传回农历y年的总天数final private static int yearDays(int y) {int i, sum = 348;for (i = 0x8000; i > 0x8; i >>= 1) {if ((lunarInfo[y - 1900] & i) != 0) sum += 1;}return (sum + leapDays(y));}//====== 传回农历y年闰月的天数final private static int leapDays(int y) {if (leapMonth(y) != 0) {if ((lunarInfo[y - 1900] & 0x10000) != 0)return 30;elsereturn 29;} elsereturn 0;}//====== 传回农历y年闰哪个月1-12 , 没闰传回0final private static int leapMonth(int y) {return (int) (lunarInfo[y - 1900] & 0xf);}//====== 传回农历y年m月的总天数final private static int monthDays(int y, int m) {if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)return 29;elsereturn 30;}//====== 传回农历y年的生肖final public String animalsYear() {final String[] Animals = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};return Animals[(year - 4) % 12];}//====== 传入月日的offset 传回干支, 0=甲子final private static String cyclicalm(int num) {final String[] Gan = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};final String[] Zhi = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};return (Gan[num % 10] + Zhi[num % 12]);}//====== 传入offset 传回干支, 0=甲子final public String cyclical() {int num = year - 1900 + 36;return (cyclicalm(num));}/** *//*** 传出y年m月d日对应的农历.* yearCyl3:农历年与1864的相差数?* monCyl4:从1900年1月31日以来,闰月数* dayCyl5:与1900年1月31日相差的天数,再加40 ?* @param cal* @return*/public Lunar(Calendar cal) {@SuppressWarnings("unused") int yearCyl, monCyl, dayCyl;int leapMonth = 0;Date baseDate = null;try {baseDate = chineseDateFormat.parse("1900年1月31日");} catch (ParseException e) {e.printStackTrace(); //To change body of catch statement use Options | File Templates.}//求出和1900年1月31日相差的天数int offset = (int) ((cal.getTime().getTime() - baseDate.getTime()) / 86400000L);dayCyl = offset + 40;monCyl = 14;//用offset减去每农历年的天数// 计算当天是农历第几天//i最终结果是农历的年份//offset是当年的第几天In用java实现简单的万年历输出的代码(2009-12-14 19:08:55)转载标签:分类:计算机类itimport java.util.Scanner;public class Zuizhong{public static void main(String[] args){Scanner input=new Scanner(System.in);System.out.println("--------------------------欢迎使用万年历程序----------------------"); System.out.print("请输入年份:");int year=input.nextInt();System.out.print("\n请输入月份:");int month=input.nextInt();//打印换行符System.out.println();//计算1900年1月1日到指定年份前一年的天数int totalDays=0;//判断是否是1900后的年份if(year>=1900){for(int i=1900;i<year;i++){//判断是否闰年,闰年加366天,否则加365天if((i%4==0 && i%100!=0)||(i%400==0))totalDays+=366;else totalDays+=365;}//计算指定年份1月到指定月份1号之间的天数int daysOfMonth=0;int days;for(int i=1;i<month;i++){switch(i){case 2:if((year%4==0 && year%100!=0)|| year%400==0) days=29;else days=28;break;case 4:case 6:case 9:case 11:days=30;break;default:days=31;}daysOfMonth+=days;}//获得指定年月的天数switch(month){case 2:if((year%4==0 && year%100!=0)|| year%400==0) days=29;else days=28;break;case 4:case 6:case 9:case 11:days=30;break;default:days=31;}//1900.1.1到指定年月1号之间的总天数totalDays+=daysOfMonth;//计算指定年月1号的星期数int firstDay=(totalDays)%7+1;//上一行算出的星期数是1到7,因此要转换成0-6,即星期日=0if(firstDay==7)firstDay=0;//显示月历System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");//打印1号之前的空格for(int i=0;i<firstDay;i++)System.out.print("\t");//打印月历for(int i=1;i<=days;i++){System.out.print(i+"\t");//如果是星期六,换行if((i-1)%7+firstDay==6)System.out.println();}}else if(year>0&&year<1900){for(int i=1899;i>year;i--){//判断是否闰年,闰年加366天,否则加365天if((i%4==0 && i%100!=0)||(i%400==0))totalDays+=366;else totalDays+=365;}//计算指定年份12月到指定月份31号之后的天数int daysOfMonth=0;int days;for(int i=12;i>=month;i--){switch(i){case 2:if((year%4==0 && year%100!=0)|| year%400==0) days=29;else days=28;break;case 4:case 6:case 9:case 11:days=30;break;default:days=31;}daysOfMonth+=days;}//获得指定年月的天数switch(month){case 2:if((year%4==0 && year%100!=0)|| year%400==0) days=29;else days=28;break;case 4:case 6:case 9:case 11:days=30;break;default:days=31;}//1900.1.1到指定年月1号之间的总天数totalDays+=daysOfMonth;//计算指定年月1号的星期数int firstDay=8-(totalDays)%7;//上一行算出的星期数是1到7,因此要转换成0-6,即星期日=0if(firstDay==7)firstDay=0;if(firstDay==8)firstDay=1;//显示月历System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");//打印1号之前的空格for(int i=0;i<firstDay;i++)System.out.print("\t");//打印月历for(int i=1;i<=days;i++){System.out.print(i+"\t");//如果是星期六,换行if((i-1)%7+firstDay==6)System.out.println();}}System.out.println("\n程序结束");}}(完)在myeclipse运行效果图:--------------------------欢迎使用万年历程序---------------------- 请输入年份:2009请输入月份:12星期日星期一星期二星期三星期四星期五星期六1 2 3 4 56 7 8 9 10 11 1213 14 15 16 17 18 1920 21 22 23 24 25 2627 28 29 30 31程序结束。
Java万年历源代码,可显示公历、农历、系统时间、国际时间
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.DefaultTableModel;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Locale;import java.util.TimeZone;public class wannianli extends JFrame implements ActionListener, MouseListener {private Calendar cld = Calendar.getInstance();//获取一个Calendar类的实例对象private String[] astr = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };private DefaultTableModel dtm = new DefaultTableModel(null, astr);private JTable table = new JTable(dtm);private JScrollPane sp = new JScrollPane(table);private JButton bLastYear = new JButton("上一年");private JButton bNextYear = new JButton("下一年");private JButton bLastMonth = new JButton("上月");private JButton bNextMonth = new JButton("下月");private JPanel p1 = new JPanel(); // 设立八个中间容器,装入布局控制日期的按钮模块private JPanel p2 = new JPanel(new GridLayout(3,2));//网格布局private JPanel p3 = new JPanel(new BorderLayout());//边界布局private JPanel p4 = new JPanel(new GridLayout(2,1));private JPanel p5 = new JPanel(new BorderLayout());private JPanel p6 = new JPanel(new GridLayout(2,2));private JPanel p7 = new JPanel(new GridLayout(2,1));private JPanel p8 = new JPanel(new BorderLayout());private JComboBox timeBox = newJComboBox(TimeZone.getAvailableIDs());//对所有支持时区进行迭代,获取所有的id;private JTextField jtfYear = new JTextField(5);// jtfYeaar年份显示输入框private JTextField jtfMonth = new JTextField(2);// jtfMouth月份显示输入框private JTextField timeField=new JTextField();//各城市时间显示框private static JTextArea jta = new JTextArea(10,5);//农历显示区private JScrollPane jsp = new JScrollPane(jta);private JLabel l = new JLabel("花江小精灵:亲!你可以直接输入年月查询.");private JLabel lt = new JLabel();private JLabel ld = new JLabel();private JLabel lu = new JLabel("农历和节气");private JLabel null1=new JLabel();private int lastTime;//private String localTime = null;private String s = null;private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd 日 hh时mm分ss秒");public wannianli() {super("花江日历过去仅留追忆,未来刚生憧憬,唯有坚守本心,把握今天 ZYT 詹永堂 ");// 框架命名this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 窗口关闭函数this.getContentPane().setLayout(new BorderLayout(9, 10));jta.setLineWrap(true);// 长度大于分配长度时候则换行jta.setFont(new Font("黑体", Font.BOLD, 16));table.setBackground(Color.white);table.setGridColor(Color.pink);// 星期之间的网格线是灰色的table.setBackground(Color.white);table.setColumnSelectionAllowed(true);// 将table中的列设置为可选择的table.setSelectionBackground(Color.pink);// 当选定某一天时背景颜色为黑色table.setSelectionForeground(Color.GREEN);table.setBackground(new Color(184,207, 229));// 日期显示表格为浅蓝色table.setFont(new Font("黑体", Font.BOLD, 24));// 日期数字字体格式table.setRowHeight(26);// 表格的高度table.addMouseListener(this); // 鼠标监听器、lu.setFont(new Font("黑体", Font.BOLD, 22));//农历标签格氏jtfYear.addActionListener(this);// 可输入年份的文本框// 为各个按钮添加监听函数bLastYear.addActionListener(this);bNextYear.addActionListener(this);bLastMonth.addActionListener(this);bNextMonth.addActionListener(this);timeBox.addItemListener(new TimeSelectedChangedListener());// 将按钮添加到Jpane上p1.add(bLastYear);p1.add(jtfYear);// 年份输入文本框p1.add(bNextYear);p1.add(bLastMonth);p1.add(jtfMonth);p1.add(bNextMonth);p3.add(jsp, BorderLayout.SOUTH);p3.add(lu,BorderLayout.CENTER);p3.add(ld, BorderLayout.NORTH);p4.add(lt);p4.add(l);p5.add(p4, BorderLayout.SOUTH);p5.add(sp, BorderLayout.CENTER);p5.add(p1, BorderLayout.NORTH);p6.add(timeBox);p6.add(null1);p6.add(timeField);p8.add(p2,BorderLayout.CENTER);p8.add(p7,BorderLayout.SOUTH);this.getContentPane().add(p3, BorderLayout.EAST);this.getContentPane().add(p5, BorderLayout.CENTER);this.getContentPane().add(p6,BorderLayout.SOUTH);this.getContentPane().add(p8,BorderLayout.WEST);String[] strDate = DateFormat.getDateInstance().format(new Date()) .split("-");// 获取日期cld.set(Integer.parseInt(strDate[0]), Integer.parseInt(strDate[1]) - 1,0);showCalendar(Integer.parseInt(strDate[0]),Integer.parseInt(strDate[1]), cld);jtfMonth.setEditable(false);// 设置月份文本框为不可编辑jtfYear.setText(strDate[0]);jtfMonth.setText(strDate[1]);this.showTextArea(strDate[2]);ld.setFont(new Font("新宋体", Font.BOLD, 24));new Timer(lt).start();new TimeThread().start();this.setBounds(200, 200, 700, 350);this.setResizable(false);this.setVisible(true);}public void showCalendar(int localYear, int localMonth, Calendar cld) {int Days = getDaysOfMonth(localYear, localMonth) +cld.get(Calendar.DAY_OF_WEEK) -2;Object [] ai = new Object[7];lastTime = 0;for (int i = cld.get(Calendar.DAY_OF_WEEK)-1; i <= Days; i++) {ai[i%7] =String.valueOf(i-(cld.get(Calendar.DAY_OF_WEEK)-2));if (i%7 == 6){dtm.addRow(ai);ai = new Object[7];lastTime++;}}dtm.addRow(ai);}public int getDaysOfMonth(int Year, int Month) {//计算各月的天数if(Month==1||Month==3||Month==5||Month==7||Month==8||Month==10||Mont h==12){return 31;}if(Month==4||Month==6||Month==9||Month==11){return 30;}if(Year%4==0&&Year%100!=0||Year%400==0)//闰年{return 29;}else {return 28;}}public void actionPerformed(ActionEvent e)//从界面上获取年月数据{if(e.getSource() == jtfYear || e.getSource() == bLastYear || e.getSource() == bNextYear ||e.getSource() == bLastMonth || e.getSource() == bNextMonth){int m, y;try//控制输入的年份正确,异常控制{if (jtfYear.getText().length() != 4){throw new NumberFormatException();}y = Integer.parseInt(jtfYear.getText());m = Integer.parseInt(jtfMonth.getText());}catch (NumberFormatException ex){JOptionPane.showMessageDialog(this, "请输入4位0-9的数字!", "年份有误", JOptionPane.ERROR_MESSAGE);return;}ld.setText("没有选择日期");for (int i = 0; i < lastTime+1; i++){ dtm.removeRow(0);}if(e.getSource() ==bLastYear){ jtfYear.setText(String.valueOf(--y)); }if(e.getSource() ==bNextYear){jtfYear.setText(String.valueOf(++y)); }if(e.getSource() == bLastMonth){if(m == 1){jtfYear.setText(String.valueOf(--y));m = 12;jtfMonth.setText(String.valueOf(m));}else{jtfMonth.setText(String.valueOf(--m));}}if(e.getSource() == bNextMonth){if(m == 12){jtfYear.setText(String.valueOf(++y));m = 1;jtfMonth.setText(String.valueOf(m));}else{jtfMonth.setText(String.valueOf(++m));}}cld.set(y, m-1, 0);showCalendar(y, m, cld);}}public void mouseClicked(MouseEvent e){jta.setText(null);int r = table.getSelectedRow();int c = table.getSelectedColumn();if (table.getValueAt(r,c) == null){ld.setText("没有选择日期");}else{this.showTextArea(table.getValueAt(r,c));}}private void showTextArea(Object selected){ld.setText(jtfYear.getText()+"年"+jtfMonth.getText()+"月"+selected+"日");}public static void main(String[] args){JFrame.setDefaultLookAndFeelDecorated(true);JDialog.setDefaultLookAndFeelDecorated(true);new wannianli();jta.setText(today());}private void updateTimeText(String timeZoneId) {if(timeZoneId != null){TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);dateFormat.setTimeZone(timeZone);Calendar calendar = Calendar.getInstance();calendar.setTimeZone(timeZone);timeField.setText(dateFormat.format(calendar.getTime()));}else{timeField.setText(null);}}private class TimeSelectedChangedListener implements ItemListener { public void itemStateChanged(ItemEvent e) {if (e.getStateChange()==ItemEvent.SELECTED) {if (e.getItem() instanceof String) {s = e.getItem().toString();}}}}private class TimeThread extends Thread{public void run(){while(true){updateTimeText(s);try{Thread.sleep(100);}catch(InterruptedException e){e.printStackTrace();}}}}class Timer extends Thread //显示系统时间{private JLabel lt;private SimpleDateFormat fy = new SimpleDateFormat(" Gyyyy.MM.dd HH:mm:ss ");public Timer(JLabel lt){this.lt=lt;}public void run(){while(true){try{lt.setText(fy.format(new Date()));this.sleep(500);}catch(InterruptedException ex){ex.printStackTrace();}}}}final private static long[] lunarInfo= new long[] { 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554,0x056a0, 0x09ad0, 0x055d2, 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0,0x14977, 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566,0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, 0x0d4a0, 0x1d8a6, 0x0b550,0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0,0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0, 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263,0x0d950, 0x05b57, 0x056a0, 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0,0x195a6, 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, 0x04af5,0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960, 0x0d954, 0x0d4a0,0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9,0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0,0x0d260, 0x0ea65, 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520,0x0dd45, 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0 };final private static int[] year20 = new int[] { 1, 4, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1 };final private static int[] year19 = new int[] { 0, 3, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0 };final private static int[] year2000 = new int[] { 0, 3, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1 };public final static String[] nStr1 = new String[] { "", "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一","十二" };private final static String[] Gan = new String[] { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };private final static String[] Zhi = new String[] { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };private final static String[] Animals = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };// 传回农历 y年的总天数final private static int lYearDays(int y) {int i, sum = 348;for (i = 0x8000; i > 0x8; i >>= 1) {if ((lunarInfo[y - 1900] & i) != 0)sum += 1;}return (sum + leapDays(y));}// 传回农历 y年闰月的天数final private static int leapDays(int y) {if (leapMonth(y) != 0) {if ((lunarInfo[y - 1900] & 0x10000) != 0)return 30;elsereturn 29;} elsereturn 0;}// 传回农历 y年闰哪个月 1-12 , 没闰传回 0final private static int leapMonth(int y) {return (int) (lunarInfo[y - 1900] & 0xf);}//传回农历 y年m月的总天数final private static int monthDays(int y, int m) {if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)return 29;elsereturn 30;}// 传回农历 y年的生肖final public static String AnimalsYear(int y) {return Animals[(y - 4) % 12];}//传入月日的offset 传回干支,0=甲子final private static String cyclicalm(int num) {return (Gan[num % 10] + Zhi[num % 12]);}// 传入 offset 传回干支, 0=甲子final public static String cyclical(int y) {int num = y - 1900 + 36;return (cyclicalm(num));}// 传出农历.year0 .month1 .day2 .yearCyl3 .monCyl4 .dayCyl5 .isLeap6final private long[] Lunar(int y, int m) {long[] nongDate = new long[7];int i = 0, temp = 0, leap = 0;Date baseDate = new GregorianCalendar(1900 + 1900, 1,31).getTime();Date objDate = new GregorianCalendar(y + 1900, m, 1).getTime();long offset = (objDate.getTime() - baseDate.getTime()) / 86400000L;if (y < 2000)offset += year19[m - 1];if (y > 2000)offset += year20[m - 1];if (y == 2000)offset += year2000[m - 1];nongDate[5] = offset + 40;nongDate[4] = 14;for (i = 1900; i < 2050 && offset > 0; i++) {temp = lYearDays(i);offset -= temp;nongDate[4] += 12;}if (offset < 0) {offset += temp;i--;nongDate[4] -= 12;}nongDate[0] = i;nongDate[3] = i - 1864;leap = leapMonth(i); // 闰哪个月nongDate[6] = 0;for (i = 1; i < 13 && offset > 0; i++) {// 闰月if (leap > 0 && i == (leap + 1) && nongDate[6] == 0) { --i;nongDate[6] = 1;temp = leapDays((int) nongDate[0]);} else {temp = monthDays((int) nongDate[0], i);}// 解除闰月if (nongDate[6] == 1 && i == (leap + 1))nongDate[6] = 0;offset -= temp;if (nongDate[6] == 0)nongDate[4]++;}if (offset == 0 && leap > 0 && i == leap + 1) {if (nongDate[6] == 1) {nongDate[6] = 0;} else {nongDate[6] = 1;--i;--nongDate[4];}}if (offset < 0) {offset += temp;--i;--nongDate[4];}nongDate[1] = i;nongDate[2] = offset + 1;return nongDate;}// 传出y年m月d日对应的农历.year0 .month1 .day2 .yearCyl3 .monCyl4 .dayCyl5 .isLeap6final public static long[] calElement(int y, int m, int d) {long[] nongDate = new long[7];int i = 0, temp = 0, leap = 0;Date baseDate = new GregorianCalendar(0 + 1900, 0, 31).getTime();Date objDate = new GregorianCalendar(y, m - 1, d).getTime();long offset = (objDate.getTime() - baseDate.getTime()) / 86400000L;nongDate[5] = offset + 40;nongDate[4] = 14;for (i = 1900; i < 2050 && offset > 0; i++) {temp = lYearDays(i);offset -= temp;nongDate[4] += 12;}if (offset < 0) {offset += temp;i--;nongDate[4] -= 12;}nongDate[0] = i;nongDate[3] = i - 1864;leap = leapMonth(i); // 闰哪个月nongDate[6] = 0;for (i = 1; i < 13 && offset > 0; i++) {// 闰月if (leap > 0 && i == (leap + 1) && nongDate[6] == 0) { --i;nongDate[6] = 1;temp = leapDays((int) nongDate[0]);} else {temp = monthDays((int) nongDate[0], i);}// 解除闰月if (nongDate[6] == 1 && i == (leap + 1))nongDate[6] = 0;offset -= temp;if (nongDate[6] == 0)nongDate[4]++;}if (offset == 0 && leap > 0 && i == leap + 1) { if (nongDate[6] == 1) {nongDate[6] = 0;} else {nongDate[6] = 1;--i;--nongDate[4];}}if (offset < 0) {offset += temp;--i;--nongDate[4];}nongDate[1] = i;nongDate[2] = offset + 1;return nongDate;}public final static String getChinaDate(int day) { String a = "";if (day == 10)return"初十";if (day == 20)return"二十";if (day == 30)return"三十";int two = (int) ((day) / 10);if (two == 0)a = "初";if (two == 1)a = "十";if (two == 2)a = "廿";if (two == 3)a = "三";int one = (int) (day % 10);switch (one) {case 1:a += "一";break;case 2:a += "二";break;case 3:a += "三";break;case 4:a += "四";break;case 5:a += "五";break;case 6:a += "六";break;case 7:a += "七";break;case 8:a += "八";break;case 9:a += "九";break;}return a;}public static String today() {Calendar today = Calendar.getInstance(Locale.SIMPLIFIED_CHINESE);int year = today.get(Calendar.YEAR);int month = today.get(Calendar.MONTH) + 1;int date = today.get(Calendar.DATE);long[] l = calElement(year, month, date);StringBuffer sToday = new StringBuffer();try {sToday.append(sdf.format(today.getTime()));sToday.append(" \n");sToday.append(" \n");sToday.append(" \n");sToday.append(" 农历");sToday.append(cyclical(year));sToday.append('(');sToday.append(AnimalsYear(year));sToday.append(")年");sToday.append(" \n");sToday.append(" ");sToday.append(nStr1[(int) l[1]]);sToday.append("月");sToday.append(getChinaDate((int) (l[2])));return sToday.toString();} finally {sToday = null;}}private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年M月d日 EEEEE");public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) { }}。
Java实现简单的万年历
Java实现简单的万年历本⽂实例为⼤家分享了Java实现简单万年历的具体代码,供⼤家参考,具体内容如下1 要求1、输⼊年份;2、输⼊⽉份;3、输出某年某⽉的⽇历。
2 思路1、实现从控制台接收年和⽉,判断是否是闰年(判断是否是闰年:能被4整除但不能被100整除;或者能被400整除);2、计算输⼊⽉份的天数;3、计算该⽉第⼀天是星期⼏;3.1 计算输⼊年份距离1900年1⽉1⽇的天数;3.2 计算输⼊⽉份之前的天数(从当年年初开始);3.3 将以上两组数据进⾏求和;3.4 已知该⽉之前的天数,计算输⼊⽉份的第⼀天是星期⼏(从1900年1⽉1⽇(星期⼀)开始推算: 星期⼏ = 1 + 天数差 % 7 )。
4、按格式输出该⽉⽇历。
3 源代码import java.util.Scanner;public class index {//每个⽉的天数public static int monthday(int month, int year) {if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {int[] day = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};return day[month];} else {int[] day = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};return day[month];}}//⽉份总天数public static int monthdays(int month, int year) {int totaldays = 0;for (int i = 1; i < month; i++) {totaldays = totaldays + monthday(i, year);}return totaldays;}//距离1900年的年份总天数public static int yeardays(int year){int yeardays = 0;for (int i = 1900;i<year;i++){if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {yeardays = yeardays+366;} else {yeardays = yeardays+365;}}System.out.println(year+"年距离1900年的总天数"+yeardays);return yeardays;}//输出⽇历public static void printCalendar(int month,int year){int totaldays = 0;if (year > 0) {if (month > 0 && month < 13) {//距离1900年1⽉1⽇总天数totaldays = monthdays(month,year)+yeardays(year);System.out.println(year+"年"+month+"⽉1⽇距离1900年的总天数:"+totaldays);System.out.println("\n**********"+year+"年"+month+"⽉的⽇历为**********");System.out.println("⼀\t⼆\t三\t四\t五\t六\t⽇\t");int week = 1+totaldays%7;//根据1⽇为周⼏输出空格for(int i=1;i<week;i++){System.out.print(" \t");}//输⼊具体⽇期for(int i=1;i<=monthday(month,year);i++){System.out.print(i+"\t");if(week==7){week = 1;//重置为星期⼀System.out.println();}else{week++;}}} else {System.out.println("输⼊的⽉份不合法!");}} else {System.out.println("输⼊的年份不合法!");}}//主函数public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("***********************欢迎使⽤万年历**************************");System.out.println("*********请选择你需要进⾏的操作(输⼊进⾏操作之前的数字)**********"); System.out.println("********************1.查询某年某⽉的⽇历************************");System.out.println("********************2.结束操作*********************************");System.out.print("\n请选择你需要进⾏的操作:");int a = scanner.nextInt();for (int i=0;i>=0;i++) {switch (a) {case 1:System.out.print("请选择年份:");int year = scanner.nextInt();System.out.print("请选择⽉份:");int month = scanner.nextInt();printCalendar(month, year);System.out.print("\n请选择你需要进⾏的操作:");a = scanner.nextInt();break;case 2:System.out.println("退出程序成功!");return;}}}}4 结果截图注意:我的周⽇是在最后⼀栏以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JAVA实现的简单万年历代码
JAVA实现的简单万年历代码本⽂实例讲述了JAVA实现的简单万年历。
分享给⼤家供⼤家参考,具体如下:import java.util.Scanner;public class PrintCalendar {public static void main(String[] args) {int years = 0;int month = 0;int days = 0;boolean isRun = false;//從控制台輸⼊年,⽉Scanner input = new Scanner(System.in);System.out.print("請輸⼊年份:");years = input.nextInt();System.out.print("請輸⼊⽉份:");month = input.nextInt();System.out.println("\n*********"+years+"年"+month+"⽉⽇曆表************");//判断是否是闰年if((years % 4 == 0 && years % 100 != 0) || (years % 400 == 0)){isRun = true;}int totalDays = 0; //累計天數//計算距離1900年1⽉1⽇的天數for(int i = 1900; i < years; i++){if((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0)){totalDays = totalDays + 366;}else{totalDays = totalDays + 365;}}int beforeDays = 0;//根據⽉份判斷天數for(int j = 1; j <= month; j++){switch(j){case 1:case 3:case 5:case 7:case 8:case 10:case 12:days = 31;break;case 4:case 6:case 9:case 11:days = 30;break;case 2:if(isRun){days = 29;}else{days = 28;}default:System.out.println("输⼊⽉份不正确!!");}if(j < month){beforeDays = beforeDays + days;}}totalDays = totalDays + beforeDays; //統計到⽬前總天數int firstDayOfMonth = 0;int temp = 1 + totalDays % 7 ;if(temp == 7){firstDayOfMonth = 0; //週⽇}else{firstDayOfMonth = temp;}/* 输出⽇历 */System.out.println("星期⽇\t星期⼀\t星期⼆\t星期三\t星期四\t星期五\t星期六");for(int k = 0; k < firstDayOfMonth; k++){System.out.print("\t");}for(int m = 1; m <= days; m++){System.out.print( m + "\t");if((totalDays + m) % 7 == 6){System.out.print("\n");}}}}关于万年历的制作感兴趣的朋友还可参考本站在线⼯具:希望本⽂所述对⼤家Java程序设计有所帮助。
JAVA控制台万年历代码
days += 31;
yearDay = 31;
} else if (month == 2) {
if (years % 4 == 0 && years % 100 != 0
+ work[No] + "】\t编号:No." + No);
No++;
continue;
} else {
No++;
continue;
}
}
No = 0; //输入菜单
System.out.print("\n\n当月日期:" + years + "年" + monthsDay + "月");
prox(); //上月
}else if(answer.equals("d") || answer.equals("D")|| answer.equals("2")){
ultimo(); //下月
}else if(answer.equals("w") || answer.equals("W")|| answer.equals("3")) {
|| month == 11) {
days += 30;
yearDay = 30;
}
}
if (monthsDay == 1 || monthsDay == 3 || monthsDay == 5
用JAVA编万年历和记事本
用JAVA编写万年历!万年历其实可分为5步来做,下面我们来详细分析下步骤:a:先输出提示语句,并接受用户输入的年、月。
b:根据用户输入的年,先判断是否是闰年。
C:根据用户输入的月来判断月的天数。
D:用循环计算用户输入的年份距1900年1月1日的总天数。
E:用循环计算用户输入的月份距输入的年份的1月1日共有多少天。
F:相加D与E的天数,得到总天数。
G:用总天数来计算输入月的第一天的星期数。
H:根据G的值,格式化输出这个月的日历!其实有些步骤是可以合并的,这得靠大家自己的习惯了,下面我们就来一步一步来完成万年历。
<这里只提供讲解,没有源码下载哦!其实大家不必去网上下载,那有意思吗?我们学习是为了什么啊!要下载那就不必来这了!呵呵,发表下自己的看法!>这里大家肯定都能看得懂的,1:这是为了美化,我们编的程序是让别人看的,所以就要输出个标题的。
2:这里就是用来接收用户输入的信息,并赋值给两个变量!这个相信大家都能看得懂!3:这里我们就要开始万年历的真正开发了,看完代码大家都知道这是要进行闰年判断了,这里大家要先明白判断闰年的条件是什么?(条件:这个年首先不是整百年就是最后两位是0的年,因为如果是的话就要除以400了,并且还要能被4整除的或者就是整百年能被400除尽的年是闰年)这里声明了一个boolean值,用来储存是否是闰年,因为咱们后面要用得到的!下面就要进行第二步了,来处理用户输入的月了,看完后大家都明白了吧!这里要用if来判断输入的月份,我们给月份分类,有这几种情况:有31天,有30天,有29天,有28天,下面我们就要想明白每个类的判断条件了?(条件:有31天的月是1、3、5、7、8、10、12,有30天的月是4、6、9、11,剩下就是2月了,它有两种情况,就是根据第一步的boolean值来判断了,如果为true就是29天,为false则是28天了。
)这里用到了一个变量tian,因为咱们后面还要用到的,这些变量可以在做到后面再回来补上的。
Java万年历
J a v a万年历一项目概述:这个项目是一个简单的Java万年历,可以实现所有年份的公历日期的查询,并且在相应的日期做备忘录,以及可以显示当前的日期以及时间。
使用的是Oracle数据库进行连接。
二具体功能介绍:(1)万年历查询:点击图形界面中的上年、下年键用来调整要查询的年份,或者可以直接在上年下年按钮直接的文本框中输入年份(负数表示公元前),以回车结束;点击上月或者下月来调整要查询的月份,然后可以看到这个月的每一天所对应的星期。
(2)Clock功能:在万年历下面显示当前的年月日时分秒,相当于一个时钟的功能。
(3)记事本功能:可以任选某年某月的某一天,单击,在右侧会出现这一天的备忘录,如果存在,则显示某年某月某日有日志记载,是否想看,否则,则在文本框中显示无记录;然后可以编辑这一天的备忘录,编辑好了之后,点击保存日志,弹出对话框某年某月某日保存日志吗,点击保存,则日志被保存,反之未被保存;若想删除某日的日志,则单击这一天,然后点击右侧的删除日志,显示删除某年某月某日的日志吗,点击是,则日志被删除。
从文件中读取备忘录的内容,用数据库进行存储和删除操作。
三设计与实现(需要附全部代码,GUI自动生成代码除外):1 类的设计(继承、多态、数据结构):核心类是Month,Year,NotePad,Clock,DBAccess,CalendarPad.(其中继承用粗体,接口用粗斜体,数据结构是哈希表,用粗下划线,多态用斜体+点点短线式下划线)2 Java IO (文件访问):用的是粗体+浪线3 JDBC (数据库访问):使用Oracle数据库连接,是直连(双下划线)数据库是:create table mynotes(mydate varchar2(50) primary key,note varchar2(100) not null);4 Socket + Multi-Thread:斜体(定义在Clock中的Thread t)5 GUI (用户界面):点下划线来表示GUI用户界面6 其他功能:(无)以下是全部代码(共六个.J a v a文件)//对月份的选择package javaapplication13;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Month extends Box implements ActionListener//ActionListener接口{int month;JTextField showMonth=null;JButton RMonth,NMonth;CalendarPad cal;public Month(CalendarPad c){super(BoxLayout.X_AXIS);this.cal=c;showMonth=new JTextField(2);month=c.getMonth();showMonth.setEditable(false);showMonth.setForeground(Color.blue);showMonth.setFont(new Font("TimesRomn",Font.BOLD,16));NMonth=new JButton("下月");RMonth=new JButton("上月");add(RMonth);add(showMonth);add(NMonth);RMonth.addActionListener(this);NMonth.addActionListener(this);showMonth.setText(""+month);}public void setMonth(int month){if(month<=12&&month>=1){this.month=month;}else{this.month=1;}showMonth.setText(""+month);}public int getMonth(){return month;}public void actionPerformed(ActionEvent e) {if(e.getSource()==RMonth){if(month>=2){month=month-1;cal.setMonth(month);cal.setCal(cal.getYear(),month);}else if(month==1){month=12;cal.setMonth(month);cal.setCal(cal.getYear(),month);}showMonth.setText(""+month);}else if(e.getSource()==NMonth){if(month<12){month=month+1;cal.setMonth(month);cal.setCal(cal.getYear(),month);}else if(month==12){month=1;cal.setMonth(month);cal.setCal(cal.getYear(),month);}showMonth.setText(""+month);}}}//对年分的选择package javaapplication13;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Year extends Box implements ActionListener//ActionListener接口{int year;JTextField showYear=null;JButton NYear,RYear;CalendarPad cal;public Year(CalendarPad c){super(BoxLayout.X_AXIS);showYear=new JTextField(4);showYear.setForeground(Color.blue);showYear.setFont(new Font("TimesRomn",Font.BOLD,14));this.cal=c;year=cal.getYear();NYear=new JButton("下年");RYear=new JButton("上年");add(RYear);add(showYear);add(NYear);showYear.addActionListener(this);RYear.addActionListener(this);NYear.addActionListener(this);}public void setYear(int year){this.year=year;showYear.setText(""+year);}public int getYear(){return year;}public void actionPerformed(ActionEvent e){if(e.getSource()==RYear){year=year-1;showYear.setText(""+year);cal.setYear(year);cal.setCal(year,cal.getMonth());}else if(e.getSource()==NYear){year=year+1;showYear.setText(""+year);cal.setYear(year);cal.setCal(year,cal.getMonth());}else if(e.getSource()==showYear){try{year=Integer.parseInt(showYear.getText());showYear.setText(""+year);cal.setYear(year);cal.setCal(year,cal.getMonth());}catch(NumberFormatException ee){showYear.setText(""+year);cal.setYear(year);cal.setCal(year,cal.getMonth());}}}}//对备忘录的操作package javaapplication13;import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;import javax.swing.event.*;import java.io.*;public class NotePad extends JPanel implements ActionListener{JTextArea text;JButton save_log,del_log;Hashtable table;JLabel mes_label;int year,month,day;File file;CalendarPad calendar;public NotePad(CalendarPad calendar)//构造函数{this.calendar=calendar;Calendar now = Calendar.getInstance();int hour=now.get(Calendar.HOUR);int minute=now.get(Calendar.MINUTE);year=calendar.getYear();month=calendar.getMonth();day=calendar.getDay();;table=calendar.getHashtable();file=calendar.getFile();mes_label=new JLabel(""+year+"年"+month+"月"+day+"日"+" "+hour+":"+minute,JLabel.CENTER);mes_label.setFont(new Font("TimesRoman",Font.BOLD,16));mes_label.setForeground(Color.MAGENTA);text=new JTextArea(10,8);save_log=new JButton("保存日志") ;del_log=new JButton("删除日志") ;save_log.addActionListener(this);del_log.addActionListener(this);setLayout(new BorderLayout());JPanel pSouth=new JPanel();add(mes_label,BorderLayout.NORTH);pSouth.add(save_log);pSouth.add(del_log);add(pSouth,BorderLayout.SOUTH);add(new JScrollPane(text),BorderLayout.CENTER);}public void actionPerformed(ActionEvent e){if(e.getSource()==save_log){saveLog(year,month,day);}else if(e.getSource()==del_log){delLog(year,month,day);}}public void setYear(int year){this.year=year;}public int getYear(){return year;}public void setMonth(int month){this.month=month;}public int getMonth(){return month;}public void setDay(int day){this.day=day;}public int getDay(){return day;}public void setMesLabel(int year,int month,int day){mes_label.setText(""+year+"年"+month+"月"+day+"日"); }public void setText(String s){text.setText(s);}public void getLog(int year,int month,int day){String key=""+year+""+month+""+day;try{FileInputStream inOne=new FileInputStream(file);ObjectInputStream inTwo=new ObjectInputStream(inOne);table=(Hashtable)inTwo.readObject();inOne.close();inTwo.close();}catch(Exception ee){}if(table.containsKey(key)){String m=""+year+"年"+month+"月"+day+"这一天有日志记载,想看吗?";int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);if(ok==JOptionPane.YES_OPTION){text.setText((String)table.get(key));}else{text.setText("");}}else{text.setText("无记录");}}public void saveLog(int year,int month,int day){String 日志内容=text.getText();String key=""+year+""+month+""+day;String m=""+year+"年"+month+"月"+day+"保存日志吗?";int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);if(ok==JOptionPane.YES_OPTION){try{FileInputStream inOne=new FileInputStream(file);ObjectInputStream inTwo=new ObjectInputStream(inOne);table=(Hashtable)inTwo.readObject();inOne.close();inTwo.close();table.put(key,日志内容);FileOutputStream out=new FileOutputStream(file);ObjectOutputStream objectOut=new ObjectOutputStream(out);objectOut.writeObject(table);objectOut.close();out.close();}catch(Exception ee){}}//向数据库中添加数据。
java编写的万年历
System.exit(0);
}
});
setTitle("万年历 06专升本一班 06303103 冯占魁");
setSize(550,450); //////////////////////////////////////////////////定义万年历方框的大小为550*450
p1.add(textfield); /////////////////////////////////////////////////输入年份
p1.add(lmonth);
p1.add(Month);
Month.add("一月");
Month.add("二月");
Month.add("三月");
days[6].setLabel("Sat");
if ( myday>0)
{
int blank= myday;
for( ;blank>0;blank--,count++)
{
days[count].setLabel("");
}
}
for(int i=1;i<=mytotdays; i++,count++)
Year.add("1900");
Year.addItemListener(new myLis(this));
for(int i=0;i<49;i++)
{
days[i]=new Button("");
java万年历控制台输出
import java.util.*;import java.awt.BorderLayout;//边界布局import java.awt.Color;import java.awt.GridLayout;import java.awt.Toolkit;import java.awt.event.*;import javax.swing.*;public class wannianli {public static void main(String[] args) {new MainFrame();}}class MainFrame extends JFrame {JPanel panel = new JPanel(new BorderLayout());JPanel panel1 = new JPanel();JPanel panel2 = new JPanel(new GridLayout(7, 7));JLabel[] label = new JLabel[49];JLabel y_label = new JLabel("年份");JLabel m_label = new JLabel("月份");JTextField T1=new JTextField(6);JTextField T2=new JTextField(6);JButton JB1=new JButton("转到");int re_year, re_month;int x_size, y_size;String year_num;Calendar now = Calendar.getInstance(); // 实例化Calendar MainFrame() {super("万年历");setSize(300, 350);x_size = (int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth());y_size = (int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight()); setLocation((x_size - 300) / 2, (y_size - 350) / 2); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);panel1.add(y_label);panel1.add(T1);panel1.add(m_label);panel1.add(T2);panel1.add(JB1);for (int i = 0; i < 49; i++) {label[i] = new JLabel("", JLabel.CENTER);// 将显示的字符设置为居中panel2.add(label[i]);}panel.add(panel1, BorderLayout.NORTH);panel.add(panel2, BorderLayout.CENTER);panel.setBackground(Color.white);panel1.setBackground(Color.white);panel2.setBackground(Color.white);Init();JB1.addActionListener(new ClockAction());setContentPane(panel);setVisible(true);setResizable(false);}public void Init() {int year, month_num, first_day_num;String log[] = { "日", "一", "二", "三", "四", "五", "六" };for (int i = 0; i < 7; i++) {label[i].setText(log[i]);}for (int i = 0; i < 49; i = i + 7) {label[i].setForeground(Color.red); // 将星期日的日期设置为红色}for (int i = 6; i < 49; i = i + 7) {label[i].setForeground(Color.green);// 将星期六的日期设置为绿色}month_num = (int) (now.get(Calendar.MONTH)); // 得到当前时间的月份year = (int) (now.get(Calendar.YEAR)); // 得到当前时间的年份 cMake(year,month_num);}class ClockAction implements ActionListener {public void actionPerformed(ActionEvent arg0) {int c_year, c_month;c_year = Integer.parseInt(T1.getText().toString()); // 得到当前所选年份c_month = Integer.parseInt(T2.getText().toString()) - 1;// 得到当前月份,并减1,计算机中的月为0-11cMake(c_year,c_month);}}static int isyear(int year){if(year%4==0&&year%100!=0||year%400==0)return 1;else return 0;}public void cMake(int y,int m){Calendar 日历=Calendar.getInstance();日历.set(y,m,1);int星期几=日历.get(Calendar.DAY_OF_WEEK)-1;int days=30;switch(m){case 0:case 2:case 4:case 6:case 9:case 11: days=30;break;case 3:case 5:case 7:case 8:case 10: days=31;break;case 1:if(isyear(y)==1)days=29;else days=28;break;}for(int i = 7; i < 49; i++){label[i].setText("");}String a[]=new String[星期几+days];for(int i=0;i<星期几 ;i++){a[i]="";}for(int i=星期几,n=1;i<a.length;i++,n++){a[i]=String.valueOf(n);}for(int i=0;i<a.length;i++){label[i+7].setText(a[i]);}}}。
用Java程序编写万年历程序的设计报告
用Java程序编写万年历程序的设计报告一、引言万年历是一种常见的工具,用于显示特定日期的星期几、农历日期、节气等信息。
本设计报告旨在介绍使用Java编写万年历程序的设计过程和实现细节。
二、需求分析1. 显示当前日期的星期几和农历日期;2. 支持用户输入指定日期,显示该日期的星期几和农历日期;3. 显示当月的日历,并标记当天;4. 支持用户选择不同年份和月份,显示相应的日历;5. 显示当天的节气。
三、设计思路1. 日期计算:使用Java提供的日期和时间类,如`java.util.Calendar`,来进行日期计算和格式化;2. 农历计算:根据农历算法,计算指定日期的农历日期和节气;3. 用户界面:使用Java图形用户界面(GUI)库,如`javax.swing`,来实现用户界面;4. 数据展示:使用文本框、标签等组件来展示日期、星期几、农历日期和节气。
四、程序实现1. 创建Java项目,并导入所需的库;2. 创建主界面窗口,设置布局和组件;3. 添加日期选择器,用于选择年份和月份;4. 添加按钮,用于触发日期查询和切换月份;5. 根据用户选择的日期,计算并显示星期几、农历日期和节气;6. 根据用户选择的年份和月份,计算并显示当月的日历;7. 标记当天的日期;8. 添加事件监听器,处理用户的操作。
五、代码示例```java// 导入所需的库import java.util.Calendar;import java.util.Date;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class CalendarProgram extends JFrame {private JLabel dateLabel;private JLabel weekdayLabel;private JLabel lunarLabel;private JLabel festivalLabel;private JPanel calendarPanel;public CalendarProgram() {// 设置窗口标题和大小setTitle("万年历程序");setSize(800, 600);// 创建主界面布局和组件JPanel mainPanel = new JPanel(); dateLabel = new JLabel();weekdayLabel = new JLabel(); lunarLabel = new JLabel();festivalLabel = new JLabel();calendarPanel = new JPanel();// 将组件添加到主界面布局中 mainPanel.add(dateLabel);mainPanel.add(weekdayLabel); mainPanel.add(lunarLabel);mainPanel.add(festivalLabel);mainPanel.add(calendarPanel); // 设置主界面布局和显示setContentPane(mainPanel);setVisible(true);}public void updateCalendar(Date selectedDate) {// 根据选择的日期更新界面显示Calendar calendar = Calendar.getInstance();calendar.setTime(selectedDate);// 计算并显示星期几、农历日期和节气int weekday = calendar.get(Calendar.DAY_OF_WEEK); String lunarDate = calculateLunarDate(calendar);String festival = calculateFestival(calendar);dateLabel.setText("日期:" + selectedDate.toString()); weekdayLabel.setText("星期几:" + weekday);lunarLabel.setText("农历日期:" + lunarDate);festivalLabel.setText("节气:" + festival);// 计算并显示当月的日历int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH);int daysInMonth = calculateDaysInMonth(year, month); displayCalendar(year, month, daysInMonth);}private String calculateLunarDate(Calendar calendar) {// 根据农历算法计算农历日期// 实现略}private String calculateFestival(Calendar calendar) {// 根据日期计算节气// 实现略}private int calculateDaysInMonth(int year, int month) {// 计算指定年份和月份的天数// 实现略}private void displayCalendar(int year, int month, int daysInMonth) { // 显示当月的日历// 实现略}public static void main(String[] args) {CalendarProgram program = new CalendarProgram();program.updateCalendar(new Date());}}```六、总结通过使用Java编写万年历程序,我们可以实现日期计算、农历计算和节气计算等功能,并通过图形界面展示给用户。
java万年历程序代码
package pack;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Calendar;import java.util.Date;public class rili extends JFrame implements ActionListener { JButton b_today, b_query;JLabel lb_Year, lb_Month;JButton b_week[] = new JButton[7];JButton b_day[][] = new JButton[6][7];Container thisContainer;JPanel pUp;JPanel pCenter;JPanel pCenter_week, pCenter_day;JComboBox year, month;public void init() {b_today = new JButton("Today");b_query = new JButton("Query");setTitle("日历");lb_Year = new JLabel("Year");lb_Month = new JLabel("Month");year = new JComboBox();month = new JComboBox();setDate();pUp = new JPanel();pUp.add(lb_Year);pUp.add(year);pUp.add(lb_Month);pUp.add(month);pUp.add(b_today);pUp.add(b_query);b_today.addActionListener(this);b_query.addActionListener(this);pCenter = new JPanel();pCenter_week = new JPanel();b_week[0] = new JButton("星期日");b_week[1] = new JButton("星期一");b_week[2] = new JButton("星期二");b_week[3] = new JButton("星期三");b_week[4] = new JButton("星期四");b_week[5] = new JButton("星期五");b_week[6] = new JButton("星期六");b_week[0].setSize(400, 200);b_week[1].setSize(400, 200);b_week[2].setSize(400, 200);b_week[3].setSize(400, 200);b_week[4].setSize(400, 200);b_week[5].setSize(400, 200);b_week[6].setSize(400, 200);for (int i = 0; i < 7; i++) {b_week[i].setEnabled(false);pCenter_week.add(b_week[i]);}pCenter_day = new JPanel();for (int cols = 0; cols < 6; cols++) {for (int rows = 0; rows < 7; rows++) {b_day[cols][rows] = new JButton("");b_day[cols][rows].setSize(400, 200);this.pCenter_day.add(b_day[cols][rows]);}}pCenter_day.setLayout(new GridLayout(6, 7));setDay(Integer.parseInt(this.year.getSelectedItem().toString()),Integer.parseInt(this.month.getSelectedItem().toString()));// setDay(2011,2);pCenter.setLayout(new BorderLayout());pCenter.add(pCenter_week, "North");pCenter.add(pCenter_day, "Center");thisContainer = this.getContentPane();thisContainer.setLayout(new BorderLayout());thisContainer.add(pUp, "North");thisContainer.add(pCenter, "Center");this.setVisible(true);this.setResizable(false);this.pack();}public void setDate() {int year, month, day, week;Calendar cal = Calendar.getInstance();year = cal.get(Calendar.YEAR);month = cal.get(Calendar.MONTH);day = cal.get(Calendar.DA TE);week = cal.get(Calendar.WEEK_OF_YEAR);int year_temp = year - 4;for (int i = 0; i < 10; i++) {this.year.addItem(year_temp);year_temp += 1;}this.year.setSelectedIndex(4);for (int n = 0; n < 12; n++) {this.month.addItem(n + 1);}this.month.setSelectedIndex(month);}public void setDay(int Year, int Month) {int count;Calendar c = Calendar.getInstance();c.clear();c.set(Year, Month-1, 1);count = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 总天数System.out.print(count);int day = c.get(Calendar.DAY_OF_WEEK) - 1; // 0为星期天,6为星期六System.out.print(day);int i = 1 - day;for (int cols = 0; cols < 6; cols++) {for (int rows = 0; rows < 7; rows++) {String st = String.valueOf(i);b_day[cols][rows].setText(st);b_day[cols][rows].setEnabled(false);if (i > 0 && i <= count)b_day[cols][rows].setVisible(true);elseb_day[cols][rows].setVisible(false);i++;}}}public void actionPerformed(ActionEvent e) {if (e.getSource() == b_query) {this.setDay(Integer.parseInt(this.year.getSelectedItem().toString()), Integer.parseInt(this.month.getSelectedItem().toString()));}if (e.getSource() == b_today) {int year, month;Calendar cal = Calendar.getInstance();year = cal.get(Calendar.YEAR);month = cal.get(Calendar.MONTH)+1;this.setDay(year,month);}}public static void main(String[] args) {rili rl = new rili();rl.init();}}。
Java编写万年历
RMo nth三new .J Button(."上月一");
add(RMo nth); add(showMo nth);
add(NMo nth);
RMo nth.addActio nListe ner(this);
NMo nth.addActio nListe ner(this); showMo nth.setText(""+mo nth);
}
else if(mon th==1)
{
mon th=12;
cal.setMo nth(mo nth); cal.setCal(cal.getYear(), mon th);
}
showMo nth.setText(""+mo nth);
}
else if(e.getSource()==NMo nth)
{
if(mo nth<12)
{
mon th=mon th+1;
cal.setMo nth(mo nth);
cal.setCal(cal.getYear(), mon th);
}
else if(mon th==12)
{
mon th=1;
cal.setMo nth(mo nth);
cal.setCal(cal.getYear(), mon th);
(3)记事本功能:可以任选某年某月的某一天,单击,在右侧会出现这一天的
备忘录,如果存在,则显示某年某月某日有日志记载,是否想看,否则,则在文 本框中显示无记录;然后可以编辑这一天的备忘录,编辑好了之后,点击保存日
Java_万年历(简单)
Java_万年历(简单)1、⽅法,需要⼀个年份,⼀个⽉份。
然后在控制台输出⽇历1// 输⼊⼀个年份和⼀个⽉份显⽰⽇历2public static void printCalendar(int year, int month) {3// 转换⽇期4 Calendar calendar = Calendar.getInstance();5// 找到⽉份第⼀天6 calendar.set(year, month-1, 1);7// 找到第⼀天是周⼏ 1 周⽇ 2 周⼀8int week = calendar.get(Calendar.DAY_OF_WEEK);9//System.out.println("week: "+week);10// 获取最⼤⽇期11int dayMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);12// 循环输出13 System.out.println("星期⽇\t星期⼀\t星期⼆\t星期三\t星期四\t星期五\t星期六\t");14// 若第⼀天不为周⽇15if(week != 1) {16// 判断01是周⼏空格17for(int j = 1;j < week;j++) {18 System.out.print(" \t");19 }20 }21// 循环22for (int i = 1; i <= dayMax; i++) {23// 找到第 i 天24 calendar.set(year, month-1, i);25// 第 i 天是周⼏26int wek = calendar.get(Calendar.DAY_OF_WEEK);27 System.out.print(i + "\t");28// 周六回车29if ( wek == 7) {30 System.out.println();31 }3233 }34 }2、MainTest测试类1public static void main(String[] args) {2// 万年历测试类3 Scanner scanner = new Scanner(System.in);4boolean isTrue = true;5while(isTrue) {6 System.out.println("-------------万年历------------");7 System.out.println("1、查看⽇历");8 System.out.println("0、退出");9int key = scanner.nextInt();10switch (key) {11case 1:12 System.out.println("请输⼊年份:");13int year = scanner.nextInt();14 System.out.println("请输⼊⽉份:");15int month = scanner.nextInt();16 PerpetualCalendar.printCalendar(year, month);17 System.out.println();18break;19default:20 isTrue = false;21break;22 }23 }24 System.out.println("已退出系统...");25 }3、运⾏结果: 有帮助,就点个推荐吧,让更多⼈看到。
java万年历_java实现万年历
java万年历_java实现万年历敲了⼀下午,代码⽐较乱,思路也⽐较乱,第⼀次敲这么长的java代码,总结起来就是⽋练!!package homework;import java.io.*;import ng.*;import java.util.Scanner;import java.util.*;class year{year_month_day m=new year_month_day();void set(int y){m.year=y; m.day=1;}void year_method(){int i=1;for(i=1;i<=12;i++){System.out.println(+m.year+"年" +i+"⽉");m.month=i; m.print();}}}class year_month_day{int itag=0;int year,month,day;void set(int y,int m,int d) {year=y; month=m; day=d; }public int isLeepyear(int year) {int m;if((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0)m=1;else m=0;return m; }void print(){itag=isLeepyear(year);Calendar rili=Calendar.getInstance();rili.set(year, month-1, 1);System.out.println("⽇\t⼀\t ⼆\t 三\t 四\t 五\t 六");int week=rili.get(Calendar.DAY_OF_WEEK)-1;//System.out.println("week="+week);String a[]=new String[week+31];for(int i=0;i {a[i]="**"; }int num=0;if(itag==1&&month==2)num=29;else if(itag==0&&month==2)num=28;else if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) num=31;else num=30;for(int i=week,n=1;i ++){if(n<9) a[i]=String.valueOf(n)+" ";else a[i]=String.valueOf(n); n++;}for(int i=0;i ++)if(i%7==0){System.out.println(""); }if(a[i]==null)a[i]=" ";System.out.print(a[i]+"\t"); }System.out.print("\n\n"); } }public class year_calendar {public static void main(String[] args)System.out.println("**************************");System.out.println("* 中华万年历 *");System.out.println("* 请选择查询⽅法 *");System.out.println("*1.按年份检索 2.按年⽉⽇检索 *");System.out.println("*3.退出系统 *");System.out.println("**************************"); int n; int year,month,day;Scanner s = new Scanner(System.in);n=s.nextInt();switch(n){case 1: {System.out.println("请输⼊要检索的年份:"); year=s.nextInt();year d=new year();d.set(year);d.year_method(); break; }case 2: {System.out.println("请输⼊要检索的年⽉⽇:"); year=s.nextInt();month=s.nextInt();day=s.nextInt();year_month_day t=new year_month_day(); t.set(year, month, day);t.print(); break; }case 3:break;}}}。
java控制台输出日历
小程序:控制台输出日历package cn.java.Visualcalendar;import java.text.*;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Scanner;publicclass Visualcalendar {publicstaticvoid main(String[] args){System.out.println("请输入如下格式日期(2001-1-1):");Scanner scanner= new Scanner(System.in);//手动输入。
String str = scanner.nextLine();//将手动输入的一行字符串赋值给str。
DateFormat time = newSimpleDateFormat("yyyy-MM-dd");//按照yyyy-MM-dd的格式解析字符串。
try{ //正常情况下执行。
Date date = time.parse(str);//将字符串转换为Date数据。
Calendar calendar = new GregorianCalendar();//调用Calendar类方法。
calendar.setTime(date);//设置当前时间为输入时间。
int year = calendar.get(Calendar.YEAR);//获取输入时间的年数。
int mun = calendar.get(Calendar.MONTH);//获取输入时间的月数。
int day = calendar.getActualMaximum(Calendar.DATE);//获取输入当前月份最大天数。
int qgg = calendar.get(Calendar.DATE);//获取输入时间的天数。
Java实现打印日历的功能
Java实现打印⽇历的功能 编写⼀个程序,显⽰给定年⽉的⽇历。
程序提⽰⽤户输⼊年份和⽉份,然后显⽰该⽉的整个⽇历。
代码:1import java.util.Scanner;2public class PrintCalendar{3public static void main(String[] args){4 Scanner input=new Scanner(System.in);56 System.out.print("Enter full year(e.g.,2011): ");7int Year=input.nextInt();89 System.out.print("Enter month as a number between 1 and 12: ");10int Month=input.nextInt();1112// int year=inputYear();13//int month=inputMonth();14 printMonth(Year, Month);15 }16/*17 public static int inputYear(){18 boolean flag=true;19 Scanner input=new Scanner(System.in);20 while(flag){21 System.out.print("Enter full year(e.g.,2011): ");22 int iYear=input.nextInt();23 if(iYear>=1800){24 flag = false;25 }26 }27 return iYear;28 }2930 public static int inputMonth(){31 boolean flag=true;32 Scanner input=new Scanner(System.in);33 while(flag){34 System.out.print("Enter month as a number between 1 and 12: ");35 int iMonth=input.nextInt();36 if(iMonth>=1 && iMonth<=12){37 flag = false;38 }39 }40 return iMonth;41 }*/4243public static void printMonth(int year, int month){44 printMonthTitle(year, month);45 printMonthBody(year,month);46 }4748public static void printMonthTitle(int year, int month){49 System.out.println("\t" + getMonthName(month)+"\t" +year);50 System.out.println("-----------------------------------");51 System.out.println("Mon Tue Wed Thu Fri Sat Sun");52 }53public static String getMonthName(int month){54 String monthName="";55switch (month){56case 1: monthName="January"; break;57case 2: monthName="February"; break;58case 3: monthName="March"; break;59case 4: monthName="April"; break;60case 5: monthName="May"; break;61case 6: monthName="June"; break;62case 7: monthName="July"; break;63case 8: monthName="August"; break;64case 9: monthName="September"; break;65case 10: monthName="October"; break;66case 11: monthName="November"; break;67case 12: monthName="December"; break;68 }6970return monthName;71 }7273public static void printMonthBody(int year, int month){7475//Get start day of the week for the first date int the month76int startDay=getStartDay(year,month);7778//Get number of days in the month79int numberOfDaysInMonth = getNumberOfDaysInMonth(year,month);8081//Pad space before the first day of the month82int i=0;83for(i=1; i< startDay; i++){84 System.out.print(" ");85 }86for(i=1; i<=numberOfDaysInMonth;i++){87 System.out.printf("%-4d", i);8889if((i+startDay-1)%7==0)90 System.out.println();91 }92 System.out.println();93 }9495/** Get the start day of month/1/year */96public static int getStartDay(int year, int month){97final int START_DAY_FOR_JAN_1_1800 = 3;9899//Get the total number of days from 1/1/1800 to month/1/year100int totalNumberOfDays= getTotalNumberOfDays(year,month);101102//Return the start day for month/1/year103return (totalNumberOfDays+START_DAY_FOR_JAN_1_1800)%7;104 }105106/** Get the total number of days from January 1, 1800; */107public static int getTotalNumberOfDays(int year, int month){108int total = 0;109110//get total number of days from 1800 to 1/1/year111for(int i = 1800; i<year; i++){112if(isLeapYear(i))113 total = total + 366;114else115 total = total + 365;116 }117118//add days from January to the month prior to the calendar month119for(int i = 0; i<month;i++)120 total +=getNumberOfDaysInMonth(year, i);121122return total;123 }124125/** Get the number of days in a month */126public static int getNumberOfDaysInMonth(int year, int month){127if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) 128return 31;129if(month==4||month==6||month==9||month==11)130return 30;131if(month==2)132return isLeapYear(year)?29:28;133return 0;134 }135136/** Determine if it is a leap year */137public static boolean isLeapYear(int year){138return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);139 }140 }执⾏效果:。
Java基础之打印万年历的简单实现(案例)
Java基础之打印万年历的简单实现(案例)问题:输⼊年,⽉,打印对应年⽉的⽇历。
⽰例:问题分析:1,⾸先1970年是Unix系统诞⽣的时间,1970年成为Unix的元年,1970年1⽉1号是星期四,现在⼤多的⼿机的⽇历功能只能显⽰到1970年1⽉1⽇这⼀天; 2,要想打印某年某⽉的⽇历,⾸先应该计算出这个⽉1号是星期⼏?解决1号是星期⼏?2.1:先计算出年天数,即截⾄这⼀年1⽉1号的天数,⽤for循环,从1970年开始,闰年+366,平年+365;2.2:计算出⽉天数,即截⾄本⽉1号的天数,⽤for循环,从1⽉份开始,算出⽉天数;2.1.1:⽤到闰年判断,⽤switch来判断返回⽉天数;2.3:⽤年天数加⽉天数,求得本⽉1号距离1970年1⽉1号的总天数,⽤总天数来判断本⽉1号是星期⼏;3,判断本⽉的总天数(⽤到switch语句);4,打印⽇历;代码实现:⼀个函数实现打印PrintTitle();即实现固定的头部部分;实现Print(参数1,参数2,参数3);即实现打印⽇历主题部分;参数1(计算总天数):计算年天数,计算⽉天数;参数2传递年份;参数3传递⽉份;判断闰年设置独⽴函数;总结:解决问题前⼀定要先分析问题,把⼤问题逐步分成⼩问题,理清逻辑,实现⼩问题的逻辑,整个问题就已经实现了百分之⼋⼗;⾃下⽽上,逐步实现,函数独⽴调⽤;代码实现部分:--------------------------------------------------------以上这篇Java基础之打印万年历的简单实现(案例)就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
JAVA打印任意一年年历
printy(2012); } }
System.out.print(i); if(day == 6) {
System.out.println(); day=-1; } else System.out.print("\t"); } System.out.println(); if(day !=0) System.out.println(); }
System.out.println("日"+"\t"+"一"+"\t"+"二"+"\t"+"三
"+"\t"+"四"+"\t"+"五"+"\t"+"六"); for(int i=0; i<firstMonth(m); i++) { System.out.print("\t");
} int day=firstMonth(m); for(int i=1; i<=monthDay(m); i++, day++) {
case 2: if(isLeapYear(year)) return 29; else return 28;
default: return 0;
} }
/*
判断一个月第一天星期几
*/ public static int firstMonth(int m) { int temp=firstDay(year); for(int i =1; i<m; i++) { temp+=monthDay(i); } return temp%7; }
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.util.Scanner;
//蔡勒(Zeller)公式(只适合于1582年10月15日之后的情形):
w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1
//公式中的符号含义如下: c:世纪(年的高两位数); y:年(年的低两位数);
//m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,
//比如2005年1月1日要看作2004年的13月1日来计算); d:日; []代表取整,即只要整数部分。
//w:星期;w对7取模得:0-星期日,1-星期一,2-星期二,3-星期三,4-星期四, 5-星期五,6-星期六
//以2005年2月14日为例:c=20,y=4,m=14,d=14
//w = 4 + [4/4] + [20/4] - 2*20 + [26*(14+1)/10] + 14 - 1 = 4 + 1 + 5 - 40 + 39 + 14 - 1 = 22
//(除以7余1) 所以2005年2月14日是星期一。
public class PerpetualCalendarII {
public static void main(String[] args) {
// declare variable month,year
int month, monthDays = 0, year;
int firstDayOfMonth, a, b, w;
int count = 0;
// declare flag
boolean flag;
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份:");
year = sc.nextInt();
System.out.println("请输入月份:");
month = sc.nextInt();
// judge year is leap year or not
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { flag = true;
} else {
flag = false;
}
// get days of the month
switch (month) {
case 4:
case 6:
case 9:
case 11:
monthDays = 30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
monthDays = 31;
break;
case 2:
if (flag == true) {
monthDays = 29;
} else {
monthDays = 28;
}
}
// get the true year
if (month == 1) {
month = 13;
year -= 1;
}
if (month == 2) {
month = 14;
year -= 1;
}
// judge the firstDayOfMonth
a = year / 100;
b = year % 100;
// get the value of w
w = b + (b / 4) + (a / 4) - 2 * a + 26 * (month + 1) / 10;
if (w % 7 == 0) {
firstDayOfMonth = 1;
} else {
firstDayOfMonth = w % 7;
}
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
// output \t
for (int i = 0; i < firstDayOfMonth; i++) {
System.out.print("\t");
count++;
}
//loop days
for (int i = 1; i <= monthDays; i++) {
System.out.print(i + "\t");
count++;
if (count % 7 == 0) {
System.out.println();
}
}
}
}。