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日历的东西,我可以说它粗制滥造,并且对更有效的替代品感到好奇。
答案 0 :(得分: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();
}