日期:2014-05-20  浏览次数:20715 次

Java 日历输出问题求解呀-。-
Java code


import java.util.*;

public class CalendarTest{
    public static void main(String[] args){
        GregorianCalendar d = new GregorianCalendar();
        
        int today = d.get(Calendar.DAY_OF_MONTH);
        int month = d.get(Calendar.MONTH);
        d.set(Calendar.DAY_OF_MONTH,1);
        
        int weekday = d.get(Calendar.DAY_OF_MONTH);
        
        System.out.println("Sun Mon Tue Wed Thu Fri Sat");
        
        for(int i = Calendar.SUNDAY; i < weekday; i++)
            System.out.print("    ");
        do{
            int day = d.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%3d",day);
            
            if(day == today)
                System.out.println("*");
            else
                System.out.println(" ");
                
            if(weekday == Calendar.SATURDAY)
                System.out.println();
            d.add(Calendar.DAY_OF_MONTH,1);
            weekday = d.get(Calendar.DAY_OF_MONTH);
        }while (d.get(Calendar.MONTH) == month);
        
        if(weekday != Calendar.SUNDAY)
            System.out.println();
    }
}




我想输出 类似这样的
Sun Mon Tue Wed Thu Fri Sat
  1 2 3 ..

但是这段代码是一竖列呀-。- 求解哪里不对!

------解决方案--------------------
你这有俩问题
第一 是当天的加×号,但是不应该换行
第二 应该是 int weekday = d.get(Calendar.DAY_OF_WEEK); 此处有俩地方
即一周当中的天数 而不是一月中的天数
把这两个改好了就好了
Java code

public static void main(String[] args) {
        GregorianCalendar d = new GregorianCalendar();

        int today = d.get(Calendar.DAY_OF_MONTH);
        int month = d.get(Calendar.MONTH);
        d.set(Calendar.DAY_OF_MONTH, 1);

        int weekday = d.get(Calendar.DAY_OF_WEEK);

        System.out.println("Sun Mon Tue Wed Thu Fri Sat");

        for (int i = Calendar.SUNDAY; i < weekday; i++)
            System.out.print("    ");
        do {
            int day = d.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%3d", day);

            if (day == today)
                System.out.print("*");
            else
                System.out.print(" ");

            if (weekday == Calendar.SATURDAY)
                System.out.println();
            d.add(Calendar.DAY_OF_MONTH, 1);
            weekday = d.get(Calendar.DAY_OF_WEEK);
        } while (d.get(Calendar.MONTH) == month);

        if (weekday != Calendar.SUNDAY)
            System.out.println();
    }