輸入年份,然後列印出該年的萬年曆,以及標識出當天日期。類似於linux下的cal,linuxcal

來源:互聯網
上載者:User

輸入年份,然後列印出該年的萬年曆,以及標識出當天日期。類似於linux下的cal,linuxcal
package com.qunar.training.questionDate;


public class Permanent {
public static boolean isLeapYear(int year){//能被4整除但不能被100整除,或者能被400整除
boolean leapYear = false;
if((year % 100 == 0 && year % 400 == 0)||(year % 100 != 0 && year % 4 == 0)){
leapYear = true;
}
return leapYear;
}
public static int countDays(int year){//選個基準2015年1月1日,星期四
int countDays = 0;
int beginYear =year > 2015 ? 2015 : year;
int endYear = year > 2015 ? year : 2015;

for(int i = beginYear;i < endYear;i++ ){
if(isLeapYear(i)){
countDays += 366;
}else{
countDays += 365;
}
}
return countDays;

}
public static void showCaledar(int year){
int days = countDays(year);
int weekDay = days % 7;
if(year > 2015){
weekDay = (weekDay + 4) % 7;
}else{
weekDay = (11 -weekDay) % 7;
}
String[] monthLabels = new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
String[] weekLabels = new String[]{"Sun","Mon","Tur","Wen","Thr","Fra","Sat"};
int[] monthDay = {31,28,31,30,31,30,31,31,30,31,30,31};
for(int i = 0;i < 12;i++){
System.out.println("\n"+monthLabels[i]);
for(String weekLabel : weekLabels){ //每一周的標籤
System.out.print(weekLabel + " ");
}
System.out.println(); //下一行
for(int j = 0; j < weekDay; j++){//找到第一個日期
System.out.print(" ");
}
if(isLeapYear(year)){
monthDay[1] = 29;
}else{
monthDay[1] = 28;
}
for(int k = 1;k <= monthDay[i];k++){
if((k + weekDay - 1) % 7 == 0){
System.out.println();
}
if(k < 10){ //這裡是對齊的問題
System.out.print(k + " ");
}else{
System.out.print(k + " ");
}

}
weekDay = (weekDay + monthDay[i]) % 7;
}
}

public static void main(String[] args) {
showCaledar(2014);
}

}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.