當前位置:編程學習大全網 - 編程語言 - 初學java,今天有個日歷的擴展作業,就是從鍵盤輸入年份與月份,然後輸出該月的日歷,求大神指教,謝

初學java,今天有個日歷的擴展作業,就是從鍵盤輸入年份與月份,然後輸出該月的日歷,求大神指教,謝

妳好,這是代碼

import?java.util.Calendar;

import?java.util.Scanner;

/**

*?@author?liuxe

*?@since?JDK?1.7.0_79

*/

public?class?CalendarTest?{

public?static?void?main(String[]?args)?{

int?year?=?-1;

int?month?=?-1;

Scanner?scanner?=?new?Scanner(System.in);

System.out.println("請輸入年份");

while?(year?<?0)?{

try?{

year?=?scanner.nextInt();

}?catch?(Exception?ex)?{

year?=?-1;

scanner.nextLine();

System.out.println("輸入錯誤,請輸入年份");

}

}

System.out.println("請輸入月份");

while?(month?<?0)?{

try?{

month?=?scanner.nextInt();

if?(month?<?1?||?month?>?12)?{

throw?new?Exception();

}

}?catch?(Exception?ex)?{

month?=?-1;

scanner.nextLine();

System.out.println("輸入錯誤,請輸入月份");

}

}

System.out.println("\n日\t壹\t二\t三\t四\t五\t六\n");

Calendar?calendar?=?Calendar.getInstance();

calendar.set(year,?month?-?1,?1);

int?week?=?calendar.get(Calendar.DAY_OF_WEEK);

int?weekLoop?=?0;

int?monthDays?=?0;

//switch結構

switch?(month)?{

case?1:

monthDays?=?31;

break;

case?2:

//判斷是不是閏年

if?(((year?%?4?==?0)?&&?(year?%?100?!=?0))?||?(year?%?400?==?0))?{

monthDays?=?29;

}?else?{

monthDays?=?28;

}

break;

case?3:

monthDays?=?31;

break;

case?4:

monthDays?=?30;

break;

case?5:

monthDays?=?31;

break;

case?6:

monthDays?=?30;

break;

case?7:

monthDays?=?31;

break;

case?8:

monthDays?=?31;

break;

case?9:

monthDays?=?30;

break;

case?10:

monthDays?=?31;

break;

case?11:

monthDays?=?30;

break;

default:

monthDays?=?31;

}

//for循環

for?(int?i?=?0?-?week?+?2;?i?<=?monthDays;?i++)?{

if?(i?<=?0)?{

System.out.print("");

}?else?{

System.out.print(i);

}

weekLoop++;

System.out.print("\t");

if?(weekLoop?%?7?==?0)?{

System.out.println();

}

}

System.out.println();

scanner.close();

}

}

運行結果:

  • 上一篇:塑膠模具設計學習流程
  • 下一篇:進入新的工作環境,要怎麽樣才能與同事相處好?
  • copyright 2024編程學習大全網