完成萬年曆的製作需要用到數組、循環等知識。
編程計算輸入的月份距離1900年1月1日的天數,求出當前月之前的總天數(不包含當前輸入月分的天數,)
編程計算輸入月份的第一天是星期幾,(公式:星期幾=1+天數差%7)。
import java.util.Scanner; public class Calendar{ public static void main(String[] args){ int year; int month; int totaldays=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%400==0)||(i%4==0&&i%100!=0)){ totaldays+=366; }else{ totaldays+=365; } } //距離1900年1月1好的總天數totaldays+=monthdays(month,year); //System.out.println(totaldays); System.out.println("-------------"+year+"年"+month+"月日曆為---------------"); //開頭System.out.println("星期日/t星期一/t星期二/t星期三/t星期四/t星期五/t星期六/t"); //該月第一天是星期幾,星期幾前面就空幾格int x=1+totaldays%7; if(x==7){ x=0; } for(int i=0;i<x;i++){ System.out.print(" /t"); } int days=monthday(month,year); int i=1; while(i<=days){ System.out.print(i+" /t"); if((i+x)%7==0){ System.out.println(); } i++; } } //月份總天數public static int monthdays(int month,int year){ int totaldays=0; for(int i=1;i<month;i++){ totaldays+=monthday(i,year); } return totaldays; } //某月天數public static int monthday(int month,int year){ if((year%400==0)||(year%4==0&&year%100!=0)){ int[] arr={0,31,29,31,30,31,30,31,31,30,31,30,31}; return arr[month]; }else{ int[] arr={0,31,28,31,30,31,30,31,31,30,31,30,31}; return arr[month]; } } }以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。