scala基礎練習:實現日曆練習

package com.yc.scala


import java.util.Scanner


object MyCalendar {
  def main(args: Array[String]){
    //1.取到日期
    val input: Scanner = new Scanner(System.in);
    print("請輸入日期的年份和月份:");


    val year: Int = input.nextInt();
    val month: Int = input.nextInt();


    printf("輸入的日期是:%d年%d月\n", year, month);


    //2.判斷日期年份的平年還是閏年, 月份是多少天
    var isLeap: Boolean = false;
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
      println(year + "年是閏年");
      isLeap = true;
    } else {
      println(year + "年是平年");
    }


    var monthDay: Int = 0;
    if (month == 2) {
      if (isLeap) monthDay = 29 else monthDay = 28;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
      monthDay = 30;
    } else {
      monthDay = 31;
    }
    println(month + "月的天數是:" + monthDay);
    //3.計算日期月份的第1天是星期幾, 條件是 1900年1月1日是星期1


    var totalDay: Int = 0;
    for (tempYear <- 1900 until year) {
      if (tempYear % 4 == 0 && tempYear % 100 != 0 || tempYear % 400 == 0) {
        totalDay += 366;
      } else {
        totalDay += 365;
      }
    }


    for (tempMonth <- 1 until month) {
      if (tempMonth == 2) {
        if (isLeap) totalDay += 29 else totalDay += 28;
      } else if (tempMonth == 4 || tempMonth == 6 || tempMonth == 9 || tempMonth == 11) {
        totalDay += 30;
      } else {
        totalDay += 31;
      }
    }


    var weekday: Int = (totalDay + 1) % 7;
    println("日期月份的第1天是:星期" + weekday);


    //4.顯示日期的排序格式
    println(" 日   一    二    三   四   五   六");
    for (i <- 1 to weekday){
      print("    ");
    }
    for (i <- 1 to monthDay){
      if (i > 9){
        print(" " + i + " ");
      }else{
        print("  " + i + " ");
      }
      
      if((i + weekday) % 7 == 0){
        println();
      }
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章