0
public class calendar
{
    public static void printMonth(int numDays, int startDays)
    {
        System.out.println("Su  Mo  Tu  We  Th  Fr  Sa");

        for(int j=0; startDays >= j; j++)
        {
            if (j==0)
                System.out.print(" ");
            else
                System.out.print("    ");               
        }
        for (int i=1; numDays >= i; i++)
        {
            if (i<=7-startDays)
                System.out.print(i + "   ");    
            else if (i<10)
                System.out.print(" " + i + "  ");
            else
                System.out.print(i + "  ");
            if ((i == 7-startDays) || (i % 7+(startDays-7) == 0))           
                System.out.print("\n");                 
        }
    }
    public static void main(String args[])
    {
        printMonth(28,5);
    }
}

我用 java 写了这个来打印一个 2d 日历的东西,我可以说它是粗制滥造的,并且对更有效的替代方案感到好奇。

4

1 回答 1

2

这是一个简短的,在我看来更具可读性的形式(为了可读性而忽略尾随空格):

public static void printMonth(int numDays, int startDay) {
    System.out.println("So  Mo  Di  Mi  Do  Fr  Sa");

    int column = 0;
    for(int day = 1 - startDay; day <= numDays; day++) {
        System.out.print(day > 0 ? String.format("%2d  ", day) : "    ");
        if (++column % 7 == 0) System.out.println();
    }

    System.out.println();
}
于 2013-09-26T06:40:27.383 回答