山東大學java程序設計實驗報告6數組

內容由鍵盤輸入年份,編寫一個程序顯示當年的日曆,用 Application 程序實現,而且三個月一行。

主要步驟:

1.求某一年的某一天是星期幾的最常見的公式爲:

W = [Y-1] + [(Y-1)/4] - [(Y-1)/100] + [(Y-1)/400]+D

Y 表示年,D 代表當天這一年的第幾天,公式中的[...]指只取計算結果的整數部分。算出來的 W 除以 7,餘數是幾就是星期幾。如果餘數是 0,則爲星期日。

2. 注意平年與閏年的區別,以及二月的天數。

3. 注意年、月、日之間該有的空格

package experiment6;


import java.util.Scanner;


public class classwork6true {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int year;
int days[][] = new int[6][23];// 打印一排需要23列6行
System.out.println("Please input a year");
year = scan.nextInt();
int week = (year + year / 4 - year / 100 + year / 400) % 7;
Data data = new Data(year);


for (int Line = 0; Line < 4; Line++) { // 豎排有四個月
for (int row = 0; row < 3; row++) { // 橫排有三個月 month=row+1
for (int m = 0, n = 8 * row + week; m != -1; m++, n = 8 * row) { // 每個月數字的賦值,數組從0開始,所以m!=-1
// 可以讓程序一直循環
for (; n < 8 * row + 7; n++) { // 每週賦值
days[m][n] = data.pushDay();
// week++;
if (days[m][n] == data.monthdays(data.month)) {
m = -2;// m++,那麼m=-1,跳出循環
n = 8 * row + 7;// 跳出第一個循環
}
}
} // 一個月結束
week = (week + data.monthdays(data.month)) % 7; // 得到下個月第一天是周幾
}
// 打印環節
System.out.println(year + "-" + (data.month - 2) + "\t\t\t\t\t\t \t\t" + year + "-" + (data.month - 1)
+ "\t\t\t\t\t\t\t\t" + year + "-" + data.month);
System.out.println("日\t一\t二\t三\t四\t五\t六 \t\t日\t一\t二\t三\t四\t五\t六\t\t日\t一\t二\t三\t四\t五\t六");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 23; j++)
System.out.print(days[i][j] == 0 ? "\t" : days[i][j] + "\t"); // 三個月連續打印
System.out.println(); // 換行
}
// 三個月打印結束
}
}
}


package experiment6;
public class Data{
protected int year,month=1,day=0;
public Data(int year){
   this.year=year;
}
//計算當年是否爲閏年
public boolean isLeapYear(){
    if(year%400==0||(year%4==0&&year%100!=0))
        return true;
else
   return false;
}
//計算一個月有幾天
public int monthdays(int month){
    if(month==2&&isLeapYear())
   return 29;
else if(month==2&&!isLeapYear())
   return 28;
else if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
   return 31;
else 
return 30;
}
//推進一天,如果是月末,重新開始。
public int pushDay(){
    day++;
if(day>monthdays(month)){
   month++;
day=1;
}
return day;
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章