+ -
当前位置:首页 → 问答吧 → java print calendar

java print calendar

时间:2013-12-25

来源:互联网

引用:public class Month {
final static int DAYS_PER_WEEK = 7;
final static String[] DAYS = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
int days; //number of days in a month
int firstDay; //specifies the first day of a month

Month(int myDays, int myFirstDay){
days = myDays;
firstDay = myFirstDay;
}

void printCalendar(){
for(int i=0; i<days_per_week; i++)
System.out.print(DAYS + "\t");
System.out.println("");
System.out.print("\t" + "\t" + "\t");

for (int i=1; i<5; i++)
System.out.print(i + "\t");
System.out.println("");

for (int i=5; i<12; i++)
System.out.print(i + "\t");
System.out.println("");

for (int i=12; i<19; i++)
System.out.print(i + "\t");
System.out.println("");

for (int i=19; i<26; i++)
System.out.print(i + "\t");
System.out.println("");

for (int i=26; i<32; i++)
System.out.print(i + "\t");
System.out.println("");

}

}
OUTPUT:
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

under the method called printCalendar(),我用左for loop去print每个星期的日子
但系每一个月都咁样用for loop,成个program会好长
我想问有冇简单d既方法去print the calendar,一定要用printCalendar()呢个method

[ 本帖最后由 winnywingy 於 2013-11-20 05:52 PM 编辑 ]

作者: winnywingy   发布时间: 2013-12-25

this will work on every month.:

void printCalendar()
{
int i = 0;
for (i=0; i<firstDay; i++) // create space before startDay
System.out.print(" ");

for (i = 1; i<=days; i++)
{
if (i<10) // create ext space for less then 10
System.out.print(" " + i);
else
System.out.print(" " + i);

// new line after Sat
if ((i+firstDay)%7 == 0)
System.out.println();
}
}

作者: adammakhk   发布时间: 2013-12-25

thank you ~

but why it should be less than 10?
if (i<10) // create ext space for less then 10

作者: winnywingy   发布时间: 2013-12-25

that will good look

1-9 is one digit.
10-31 is two digit.

作者: adammakhk   发布时间: 2013-12-25

热门下载

更多