要求编程输出2008年日历,日历中要求含有月份,日期与星期(如星期一,星期二),然后统计并输出日期的个位数与相应的星期恰好相同的天数(例如2008年9月1日是星期一) 

解决方案 »

  1.   


    /**
     * @author bzwm
     * 
     */
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Calendar;
    import java.util.GregorianCalendar;public class CalendarTest {
    public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("请输入一个年份:");
    String years = in.readLine();
    CalendarPrinter cp = new CalendarPrinter(years);
    cp.printCal();
    }
    }class CalendarPrinter { private int year; private static final int monthCount = 12; public CalendarPrinter(String years) {
    if (!years.matches("\\d{4}")) {
    System.out.println("year that inputted is illagel.");
    return;
    }
    year = Integer.parseInt(years);
    } public void printCal() {
    // construct d as current date
    GregorianCalendar gCal = new GregorianCalendar(); //set year
    gCal.set(Calendar.YEAR, year);
    for (int month = 0; month < monthCount; month++) {
    gCal.set(Calendar.MONTH, month);
    printOut(gCal);
    }
    } private void printOut(Calendar cal) {
    int month = cal.get(Calendar.MONTH); // set cal to start date of the month
    cal.set(Calendar.DAY_OF_MONTH, 1); int weekday = cal.get(Calendar.DAY_OF_WEEK); // print heading
    System.out.println("Sun Mon Tue Wed Thu Fri Sat"); // indent first line of calendar
    for (int i = Calendar.SUNDAY; i < weekday; i++)
    System.out.print("    "); do {
    // print day
    int day = cal.get(Calendar.DAY_OF_MONTH);
    if (day > 0)
    System.out.print(" " + day + " ");
    else
    System.out.print("  " + day + " "); // start a new line after every Saturday
    if (weekday == Calendar.SATURDAY)
    System.out.println(); // advance d to the next day
    cal.add(Calendar.DAY_OF_MONTH, 1);
    weekday = cal.get(Calendar.DAY_OF_WEEK);
    } while (cal.get(Calendar.MONTH) == month);
    // the loop exits when d is day 1 of the next month // print final end of line if necessary
    if (weekday != Calendar.SUNDAY)
    System.out.println();
    }
    }
    没有 实现 “统计并输出日期的个位数与相应的星期恰好相同的天数”。
    printOut方法里面看看!楼主可以自行在我写的代码上加吧。
      

  2.   

    随手写了一个,比较简单,希望对你有启发。
    import java.sql.Date;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;import org.apache.commons.lang.time.DateUtils;public class Calendar2008 { public static void main(String[] args) {
    //2008年第一天
    Date firstDay = Date.valueOf("2008-1-1");
    //2009年第一天
    Date lastDay = Date.valueOf("2009-1-1");

    //日历对象
    Calendar calendar = Calendar.getInstance();

    //计数器
    int count = 0;

    //循环输出2008年日历
    for(Date day = firstDay; day.before(lastDay);){
    calendar.setTime(day);
    String dayOfWeek = null;
    switch(calendar.get(Calendar.DAY_OF_WEEK)){
    case 1 : dayOfWeek = "星期天"; break;
    case 2 : dayOfWeek = "星期一"; break;
    case 3 : dayOfWeek = "星期二"; break;
    case 4 : dayOfWeek = "星期三"; break;
    case 5 : dayOfWeek = "星期四"; break;
    case 6 : dayOfWeek = "星期五"; break;
    case 7 : dayOfWeek = "星期六"; break;
    default : break;
    }
    System.out.println(day + " : " + dayOfWeek);
    /*
     * 判断日期的个位数是否与相应的星期恰好相同
     * calendar.get(Calendar.DATE) % 10 : 得到日期的个位数
     * calendar.get(Calendar.DAY_OF_WEEK) - 1 : 对应的星期(在这里,按照国际惯例,将星期天记为第0天)
     */
    if(calendar.get(Calendar.DATE) % 10 == calendar.get(Calendar.DAY_OF_WEEK) - 1){
    count ++;
    }

    //完成循环变量day的自增操作
    day = Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.addDays(day, 1)));
    }

    System.out.println("日期的个位数与相应的星期恰好相同的天数为 : " + count);
    }
    }

    其中,org.apache.commons.lang.time.DateUtils这个类,属于apache公司的commons.lang包,可以去http://www.findjar.com/index.jsp下载。
      

  3.   

     利用calendar 类或者子类GregorianCalendar可以解决日期问题  
     不晓得要求要GUI不
     
       
      

  4.   

    利用calendar 类或者子类GregorianCalendar可以解决日期问题  
    不晓得要求要GUI不 
      

  5.   

    这是apache基金会的DateUtils工具类,非常实用,为什么不用呢?
    下面是源码:import java.text.ParseException;
    import java.text.ParsePosition;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    import java.util.TimeZone;/**
     * <p>A suite of utilities surrounding the use of the
     * {@link java.util.Calendar} and {@link java.util.Date} object.</p>
     * 
     * <p>DateUtils contains a lot of common methods considering manipulations
     * of Dates or Calendars. Some methods require some extra explanation.
     * The truncate and round methods could be considered the Math.floor(),
     * Math.ceil() or Math.round versions for dates
     * This way date-fields will be ignored in bottom-up order.
     * As a complement to these methods we've introduced some fragment-methods.
     * With these methods the Date-fields will be ignored in top-down order.
     * Since a date without a year is not a valid date, you have to decide in what
     * kind of date-field you want your result, for instance milliseconds or days.
     * </p>
     *   
     *   
     *
     * @author <a href="mailto:[email protected]">Serge Knystautas</a>
     * @author Stephen Colebourne
     * @author Janek Bogucki
     * @author <a href="mailto:[email protected]">Gary Gregory</a>
     * @author Phil Steitz
     * @author Robert Scholte
     * @since 2.0
     * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
     */
    public class DateUtils {
        
        /**
         * The UTC time zone  (often referred to as GMT).
         */
        public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
        /**
         * Number of milliseconds in a standard second.
         * @since 2.1
         */
        public static final long MILLIS_PER_SECOND = 1000;
        /**
         * Number of milliseconds in a standard minute.
         * @since 2.1
         */
        public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
        /**
         * Number of milliseconds in a standard hour.
         * @since 2.1
         */
        public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
        /**
         * Number of milliseconds in a standard day.
         * @since 2.1
         */
        public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;    /**
         * This is half a month, so this represents whether a date is in the top
         * or bottom half of the month.
         */
        public final static int SEMI_MONTH = 1001;    private static final int[][] fields = {
                {Calendar.MILLISECOND},
                {Calendar.SECOND},
                {Calendar.MINUTE},
                {Calendar.HOUR_OF_DAY, Calendar.HOUR},
                {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
                    /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
                },
                {Calendar.MONTH, DateUtils.SEMI_MONTH},
                {Calendar.YEAR},
                {Calendar.ERA}};    /**
         * A week range, starting on Sunday.
         */
        public final static int RANGE_WEEK_SUNDAY = 1;    /**
         * A week range, starting on Monday.
         */
        public final static int RANGE_WEEK_MONDAY = 2;    /**
         * A week range, starting on the day focused.
         */
        public final static int RANGE_WEEK_RELATIVE = 3;    /**
         * A week range, centered around the day focused.
         */
        public final static int RANGE_WEEK_CENTER = 4;    /**
         * A month range, the week starting on Sunday.
         */
        public final static int RANGE_MONTH_SUNDAY = 5;    /**
         * A month range, the week starting on Monday.
         */
        public final static int RANGE_MONTH_MONDAY = 6;    /**
         * <p><code>DateUtils</code> instances should NOT be constructed in
         * standard programming. Instead, the class should be used as
         * <code>DateUtils.parse(str);</code>.</p>
         *
         * <p>This constructor is public to permit tools that require a JavaBean
         * instance to operate.</p>
         */
        public DateUtils() {
            super();
        }    //-----------------------------------------------------------------------
        /**
         * Adds a number of days to a date returning a new object.
         * The original date object is unchanged.
         *
         * @param date  the date, not null
         * @param amount  the amount to add, may be negative
         * @return the new date object with the amount added
         * @throws IllegalArgumentException if the date is null
         */
        public static Date addDays(Date date, int amount) {
            return add(date, Calendar.DAY_OF_MONTH, amount);
        }    //-----------------------------------------------------------------------
        /**
         * Adds to a date returning a new object.
         * The original date object is unchanged.
         *
         * @param date  the date, not null
         * @param calendarField  the calendar field to add to
         * @param amount  the amount to add, may be negative
         * @return the new date object with the amount added
         * @throws IllegalArgumentException if the date is null
         * @deprecated Will become privately scoped in 3.0
         */
        public static Date add(Date date, int calendarField, int amount) {
            if (date == null) {
                throw new IllegalArgumentException("The date must not be null");
            }
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(calendarField, amount);
            return c.getTime();
        }
        
        //------------------------------------------------------------------------- 
        // Deprecated int constants
        // TODO: Remove in 3.0
        
        /**
         * Number of milliseconds in a standard second.
         * 
         * @deprecated Use MILLIS_PER_SECOND. This will be removed in Commons Lang 3.0.
         */
        public static final int MILLIS_IN_SECOND = 1000;
        /**
         * Number of milliseconds in a standard minute.
         * 
         * @deprecated Use MILLIS_PER_MINUTE. This will be removed in Commons Lang 3.0.
         */
        public static final int MILLIS_IN_MINUTE = 60 * 1000;
        /**
         * Number of milliseconds in a standard hour.
         * 
         * @deprecated Use MILLIS_PER_HOUR. This will be removed in Commons Lang 3.0.
         */
        public static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
        /**
         * Number of milliseconds in a standard day.
         * 
         * @deprecated Use MILLIS_PER_DAY. This will be removed in Commons Lang 3.0.
         */
        public static final int MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
        
    }
      

  6.   


    import java.applet.Applet; 
    import java.awt.*; 
    import java.util.*; public class CalendarApplet extends Applet{  static final int TOP = 70;  //顶端距离
    static final int CELLWIDTH=50,CELLHEIGHT = 30;  //单元格尺寸
    static final int MARGIN = 3;  //边界距离
    static final int FEBRUARY = 1; 

    TextField tfYear = new TextField("2004", 5); //显示年份的文本域
    Choice monthChoice = new Choice();  //月份选择下拉框
    Button btUpdate = new Button("更新");  //更新按钮
    GregorianCalendar calendar=new GregorianCalendar(); //日历对象
    Font smallFont = new Font("TimesRoman", Font.PLAIN, 15);  //显示小字体
    Font bigFont = new Font("TimesRoman", Font.BOLD, 50);  //显示大字体
    String days[] = {"星期日", "星期一", "星期二", "星期三","星期四", "星期五", "星期六"};  
    String months[] = {"一月", "二月", "三月", "四月","五月", "六月", "七月", "八月", "九月","十月", "十一月", "十二月"}; 
    int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //每个月的天数
    int searchMonth,searchYear; //查询的年份及月份 public void init(){ 
        setBackground(Color.white);  //设置背景颜色     
        searchMonth = calendar.get(Calendar.MONTH); //得到系统年份
        searchYear = calendar.get(Calendar.YEAR); //得到系统月份
        add(new Label(" 年:")); //增加组件到Applet
        tfYear.setText(String.valueOf(searchYear)); //设置文本域文字
        add(tfYear);  
        add(new Label(" 月:")); 
        monthChoice.setFont(smallFont);  //设置月份选择下拉框的显示字体
        for (int i = 0; i < 12; i++) {
         monthChoice.addItem(months[i]); //增加下拉框选项
        }
        monthChoice.select(searchMonth); //设置下拉框当前选择项
        add(monthChoice);      
        add(btUpdate); 
        int componentCount=this.getComponentCount(); //得到Applet中的组件数量
        for (int i=0;i<componentCount;i++){
         getComponent(i).setFont(smallFont); //设置所有组件的显示字体
        }     
    }

    public void paint(Graphics g){ 
        FontMetrics fontMetric;   //显示字体的FontMetrics对象
        int fontAscent; 
        int dayPos; 
        int totalWidth, totalHeight; //总的宽度,高度
        int numRows;  //行数
        int xNum, yNum;   //水平和垂直方向单元格数量 
        int numDays;  
        String dayStr;  //显示天数字符串
        int margin;        
        
        g.setColor(Color.lightGray); //设置当前颜色
        g.setFont(bigFont); //设置当前使用字体
    g.drawString(searchYear+"年",60,TOP+70); //绘制字符串
    g.drawString((searchMonth+1)+"月",200,TOP+130);   

    g.setColor(Color.black);
    g.setFont(smallFont);
        fontMetric = g.getFontMetrics();  //获取变量初值
        fontAscent = fontMetric.getAscent(); 
        dayPos = TOP + fontAscent / 2;     
        totalWidth = 7 * CELLWIDTH;  //得到总的表格宽度
        for (int i = 0; i < 7; i++) {
         g.drawString(days[i], (CELLWIDTH-fontMetric.stringWidth(days[i]))/2 + i*CELLWIDTH,dayPos-20);  //绘制表格标题栏
    }
        numRows = getNumberRows(searchYear, searchMonth); //计算需要的行的数量
        totalHeight = numRows * CELLHEIGHT; //得到总的表格高度
        for (int i = 0; i <= totalWidth; i += CELLWIDTH) {
         g.drawLine(i, TOP , i, TOP+ totalHeight); //绘制表格线
        }
        for (int i = 0, j = TOP ; i <= numRows; i++, j += CELLHEIGHT) {
        g.drawLine(0, j, totalWidth, j); //绘制表格线
        }
        xNum = (getFirstDayOfMonth(searchYear, searchMonth) + 1) * CELLWIDTH - MARGIN; 
        yNum = TOP +  MARGIN + fontAscent;      
        numDays = daysInMonth[searchMonth] + ((calendar.isLeapYear(searchYear) && (searchMonth == FEBRUARY)) ? 1 : 0); 
        for (int day = 1; day <= numDays; day++) { 
         dayStr = Integer.toString(day); 
          g.drawString(dayStr, xNum - fontMetric.stringWidth(dayStr), yNum);  //绘制字符串
          xNum += CELLWIDTH; 
          if (xNum > totalWidth) { 
              xNum = CELLWIDTH - MARGIN; 
              yNum += CELLHEIGHT; 
          } 
          } 
     }


    public boolean action(Event e, Object o){ 
    int searchYearInt; 
    if (e.target==btUpdate){ 
      searchMonth = monthChoice.getSelectedIndex();  //得到查询月份
      searchYearInt = Integer.parseInt(tfYear.getText(), 10);  //得到查询年份  
      if (searchYearInt > 1581) {
      searchYear = searchYearInt; 
      } 
    repaint();  //重绘屏幕
    return true; 
     } 
     return false; 
     } 

    private int getNumberRows(int year, int month) { //得到行数量
    int firstDay; 
    int numCells;
    if (year < 1582) { //年份小于1582年,则返回-1
    return (-1); 
    }
    if ((month < 0) || (month > 11)) {
    return (-1); 
    }
    firstDay = getFirstDayOfMonth(year, month); //计算月份的第一天
     
    if ((month == FEBRUARY) && (firstDay == 0) && !calendar.isLeapYear(year)) {
    return 4;
    }
    numCells = firstDay + daysInMonth[month]; 
    if ((month == FEBRUARY) && (calendar.isLeapYear(year))) {
    numCells++; 
    }
      return ((numCells <= 35) ? 5 : 6);  //返回行数
     } 

    private int  getFirstDayOfMonth(int year, int month) {  //得到每月的第一天
    int firstDay; 
    int i;
    if (year < 1582) { //年份小于1582年,返回-1
    return (-1); 
    }
    if ((month < 0) || (month > 11)) { //月份数错误,返回-1
    return (-1);  
    }
      firstDay = getFirstDayOfYear(year); //得到每年的第一天
      for (i = 0; i < month; i++) {
      firstDay += daysInMonth[i]; //计算每月的第一天
      }
      if ((month > FEBRUARY) && calendar.isLeapYear(year)) {
      firstDay++; 
      }
    return (firstDay % 7); 
     }  private int getFirstDayOfYear(int year){ //计算每年的第一天
    int leapYears; 
    int hundreds;
    int fourHundreds; 
    int first;
      if (year < 1582) { //如果年份小于1582年
      return (-1); //返回-1
      } 
      leapYears = (year - 1581) / 4;
      hundreds = (year - 1501) / 100;
      leapYears -= hundreds;
      fourHundreds = (year - 1201) / 400; 
      leapYears += fourHundreds;
      first=5 + (year - 1582) + leapYears % 7; //得到每年第一天
      return first; 
     } 

      

  7.   

    IT进阶者QQ群。。Fighting。75627891。学术交流。。职场征战。。工作感想。。生活闲情。。期待各位的加入助人助己。。其乐融融。。