zoukankan      html  css  js  c++  java
  • 180415_判断闰年的思路及三种 java 实现

    世纪年:能整除 100 的年份

    普通年:不能整除 100 的年份

    闰年:一年有 366 天,二月有 29 天

    平年:一年有 365 天,二月有 28 天

    对于世纪年:能整除 400 为闰年,否则为平年

    对于普通年:能整除 4 为闰年,否则为平年

    以下是代码实现:

    1、普通两层 if 嵌套语句:

    最为接近伪代码的逻辑,简单易懂

     1 if (year % 100 == 0) {
     2     if (year % 400 == 0) {
     3         System.out.println("世纪年 闰年");
     4     } else {
     5         System.out.println("世纪年 平年");
     6     }
     7 } else{
     8     if (year % 4 == 0) {
     9         System.out.println("普通年 闰年");
    10     } else {
    11         System.out.println("普通年 平年");
    12     }
    13 }

    2、IDEA 提示修改后的 if 嵌套 以及 if ... else ... if 语句:

    少用了一层嵌套,在不必要嵌套的地方去除嵌套,采用 else ... if 多分支语句

     1 if (year % 100 == 0) {
     2     if (year % 400 == 0) {
     3         System.out.println("世纪年 闰年");
     4     } else {
     5         System.out.println("世纪年 平年");
     6     }
     7 } else if (year % 4 == 0) {
     8     System.out.println("普通年 闰年");
     9 } else {
    10     System.out.println("普通年 平年");
    11 }

    3、使用三目判断运算符精简代码量后的语句:

    单条版

    1 System.out.println(year % 100 == 0 ? (year % 400 == 0 ? "世纪年 闰年" : "世纪年 平年") : (year % 4 == 0 ? "世纪年 闰年" : "世纪年 平年"));

    缩进版

    1 System.out.println(
    2         year % 100 == 0 ?
    3                 (year % 400 == 0 ? "世纪年 闰年" : "世纪年 平年") :
    4                 (year % 4 == 0 ? "世纪年 闰年" : "世纪年 平年")
    5 );

    注明:内语句的  () 不必要,是为了方便理解而加上的

  • 相关阅读:
    crystal report 用存储过程的问题。
    新的开始—2014
    C#基础(二)——C#中的构造函数
    C#基础(一)——C#中反斜杠/n与/r的区别
    Html基础(一)
    yield关键字, default关键字, 别名关键字
    让 wpf tabcontrol 延缓初始化每个tab item content
    MVC,MVP,MVVM(补充)
    Focus scope in WPF
    Wpf ItemsControl 开启UI Virtualization 的条件
  • 原文地址:https://www.cnblogs.com/ram314/p/8850015.html
Copyright © 2011-2022 走看看