關於java編寫簡易版 控制檯輸出萬年曆
阿新 • • 發佈:2018-12-25
輸入月份和年
在控制檯輸出萬年曆
結果圖如下:
程式碼`
package com.exercise;
import java.util.Scanner;
public class Demo2 {
/**
* @param args
*/
public static void main(String[] args) {
private int year = 0;
private int month = 0;
private int monthDay = 0;
//定義總天數
private int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("請輸入年份:");
year = sc.nextInt();
System.out.println("請輸入月份:");
month = sc.nextInt();
//遍歷年份的天數
for (int i = 1900; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
sum += 366;
} else {
sum += 365;
}
} // for迴圈結束 遍歷年份的天數
/*
* 由於輸入的月份,不需要遍歷,直接在下面程式碼中打出即可.
* 但是得取出輸入月份天數所以迴圈月份時把月份迴圈 ,之後下面再減掉月份.
* */
for (int i = 1; i <= month; i++) {
//當為閏年時月份
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
if (i == 2) {
monthDay = 29;
} else if (i == 4 || i == 6 || i == 9
|| i==11) {
monthDay = 30;
} else {
monthDay = 31;
}
} else {
//當為平年時
if (i==2) {
monthDay = 28;
} else if (i==4 || i==6 || i==9
|| i==11) {
monthDay = 30;
} else {
monthDay = 31;
}
}
sum += monthDay;
} // for迴圈結束 遍歷月份的天數。
System.out.println("日\t一\t二\t三\t四\t五\t六");
//總天數得減去多遍歷的那個月份的天數
sum = sum+1-monthDay;
//除以7便是從那天開始
int length = sum%7;
//之前用空格 列印
for (int i = 0; i <= length-1; i++) {
System.out.print(" \t");
}
//遍歷月份 取出多加的monthDay
for (int i = 1; i <= monthDay; i++) {
if (sum%7==6) {
System.out.print(i + "\n");
}else{
System.out.print(i + "\t");
}
//總天數自增
sum++;
}
}
}