计算闰年的Java代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1021324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:21:11  来源:igfitidea点击:

Java Code for calculating Leap Year

javaleap-yearacm-java-libraries

提问by Ibn Saeed

I am following "The Art and Science of Java" book and it shows how to calculate a leap year. The book uses ACM Java Task Force's library.

我正在关注“Java 的艺术与科学”一书,它展示了如何计算闰年。本书使用 ACM Java Task Force 的库。

Here is the code the books uses:

这是书中使用的代码:

import acm.program.*;

public class LeapYear extends ConsoleProgram {
    public void run()
    {

        println("This program calculates leap year.");
        int year = readInt("Enter the year: ");     

        boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));

        if (isLeapYear)
        {
            println(year + " is a leap year.");
        } else
            println(year + " is not a leap year.");
    }

}

Now, this is how I calculated the leap year.

现在,这就是我计算闰年的方法。

import acm.program.*;

public class LeapYear extends ConsoleProgram {
    public void run()
    {

        println("This program calculates leap year.");
        int year = readInt("Enter the year: ");

        if ((year % 4 == 0) && year % 100 != 0)
        {
            println(year + " is a leap year.");
        }
        else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
        {
            println(year + " is a leap year.");
        }
        else
        {
            println(year + " is not a leap year.");
        }
    }
}

Is there anything wrong with my code or should i use the one provided by the book ?

我的代码有什么问题还是应该使用本书提供的代码?

EDIT :: Both of the above code works fine, What i want to ask is which code is the best way to calculate the leap year.

编辑:: 上面的两个代码都可以正常工作,我想问的是哪个代码是计算闰年的最佳方法。

回答by Peter Lawrey

I suggest you put this code into a method and create a unit test.

我建议您将此代码放入一个方法中并创建一个单元测试。

public static boolean isLeapYear(int year) {
    assert year >= 1583; // not valid before this date.
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

In the unit test

在单元测试中

assertTrue(isLeapYear(2000));
assertTrue(isLeapYear(1904));
assertFalse(isLeapYear(1900));
assertFalse(isLeapYear(1901));

回答by Pete Kirkham

It's almost always wrong to have repetition in software. In any engineering discipline, form should follow function, and you have three branches for something which has two possible paths - it's either a leap year or not.

在软件中重复几乎总是错误的。在任何工程学科中,形式都应该遵循功能,并且对于具有两种可能路径的事物,您有三个分支——要么是闰年,要么不是闰年。

The mechanism which has the test on one line doesn't have that issue, but generally it would be better to separate the test into a function which takes an int representing a year and returns a boolean representing whether or not the year is a leap year. That way you can do something with it other that print to standard output on the console, and can more easily test it.

在一行上进行测试的机制没有这个问题,但通常最好将测试分成一个函数,该函数接受一个表示年份的 int 并返回一个表示该年份是否为闰年的布尔值. 这样你就可以用它做一些其他的事情,在控制台上打印到标准输出,并且可以更容易地测试它。

In code which is known to exceed its performance budget, it's usual to arrange the tests so that they are not redundant and perform the tests in an order which returns early. The wikipedia example does this - for most years you have to calculate modulo 400,100 and 4, but for a few you only need modulo 400 or 400 and 100. This is a small optimisation in terms of performance ( at best, only one in a hundred inputs are effected ), but it also means the code has less repetition, and there's less for the programmer to type in.

在已知超出其性能预算的代码中,通常会安排测试以使它们没有冗余并按提前返回的顺序执行测试。维基百科的例子就是这样做的 - 大多数年份你必须计算模 400,100 和 4,但对于少数你只需要模 400 或 400 和 100。这是性能方面的一个小优化(充其量只有一百分之一输入受到影响),但这也意味着代码的重复更少,程序员输入的更少。

回答by cletus

The correct implementation is:

正确的实现是:

public static boolean isLeapYear(int year) {
  Calendar cal = Calendar.getInstance();
  cal.set(Calendar.YEAR, year);
  return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}

But if you are going to reinvent this wheel then:

但是如果你要重新发明这个轮子,那么:

public static boolean isLeapYear(int year) {
  if (year % 4 != 0) {
    return false;
  } else if (year % 400 == 0) {
    return true;
  } else if (year % 100 == 0) {
    return false;
  } else {
    return true;
  }
}

回答by The Sphinc

Pseudo code from Wikipedia translated into the most compact Java

维基百科的伪代码翻译成最紧凑的Java

(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))

回答by Kevin P. Rice

Most Efficient Leap Year Test:

最有效的闰年测试:

if ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0))
{
    /* leap year */
}

This is an excerpt from my detailed answer at https://stackoverflow.com/a/11595914/733805

这是我在https://stackoverflow.com/a/11595914/733805 上的详细回答的摘录

回答by Seppola

boolean leapYear = ( ( year % 4 ) == 0 );

回答by Ghada Ali Othman

import javax.swing.*;
public class LeapYear {
    public static void main(String[] args) {
    int year;
String yearStr = JOptionPane.showInputDialog(null, "Enter radius: " );

year = Integer.parseInt( yearStr );

boolean isLeapYear;
isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);  

 if(isLeapYear){ 
JOptionPane.showMessageDialog(null, "Leap Year!"); 
 }  
 else{
JOptionPane.showMessageDialog(null, "Not a Leap Year!"); 
    }
    }
    }

回答by Vincent

This is what I came up with. There is an added function to check to see if the int is past the date on which the exceptions were imposed(year$100, year %400). Before 1582 those exceptions weren't around.

这就是我想出的。有一个附加的函数来检查 int 是否超过了施加例外的日期(year$100,year %400)。在 1582 年之前,这些例外并不存在。

import java.util.Scanner;

public class lecture{


public static void main(String[] args) {
    boolean loop=true;
    Scanner console = new Scanner( System.in );
    while (loop){
        System.out.print( "Enter the year: " );

        int year= console.nextInt();
        System.out.println( "The year is a leap year: "+ leapYear(year) );
        System.out.print( "again?: " );
        int again = console.nextInt();
        if (again == 1){
            loop=false;
        }//if
    }
}
public static boolean leapYear ( int year){
    boolean leaped = false;
    if (year%4==0){
        leaped = true;
        if(year>1582){
            if (year%100==0&&year%400!=0){
                leaped=false;
            }
        }
    }//1st if
    return leaped;
}
} 

回答by user2911887

public static void main(String[] args)
{

String strDate="Feb 2013";
        String[] strArray=strDate.split("\s+");        

        Calendar cal = Calendar.getInstance();
        cal.setTime(new SimpleDateFormat("MMM").parse(strArray[0].toString()));
        int monthInt = cal.get(Calendar.MONTH);
        monthInt++;
        cal.set(Calendar.YEAR, Integer.parseInt(strArray[1]));          
        strDate=strArray[1].toString()+"-"+monthInt+"-"+cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println(strDate);    



}

回答by VirusCD

    import java.util.Scanner;

    public class LeapYear {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the year then press Enter : ");
        int year = input.nextInt();

        if ((year < 1580) && (year % 4 == 0)) {
            System.out.println("Leap year: " + year);
        } else {
            if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
                System.out.println("Leap year: " + year);
            } else {
                System.out.println(year + " not a leap year!");
            }

        }
    }
}