创建一个关于闰年的Java程序

时间:2013-07-02 00:20:36

标签: java

我需要制作一个程序(使用BlueJ),该程序需要一年时间并告诉用户它是否是闰年。年份必须在1582年之后。任何可被4整除的年份都是闰年,除非它可被100整除但不能被400整除。最后一部分就是我遇到的麻烦。

这就是我所拥有的:

import java.util.Scanner;
public class IfElseEx2
{
    public static void main(){ Scanner S = new Scanner(System.in);
    System.out.println("Please enter a year");
    int year = S.nextInt();
    if ((year / 400)= 0) {
        System.out.print("That year was not a leap year");
    }
    else if (year<1582){
        System.out.print ("Please enter a year after 1582");
    }
    else if ((year % 4)==0){
        System.out.println("This year was a leap year");
    }
    else if ((year % 4)!= 0){
        System.out.print("This year was not a leap year");
    }
}

非常感谢任何帮助

4 个答案:

答案 0 :(得分:2)

在这一行

if ((year / 400)= 0) {

您需要使用比较运算符==而不是赋值运算符=。尝试

if ((year / 400) == 0) {

此外,您需要涵盖诸如1900年可被100整除但 400但不是闰年的情况。

答案 1 :(得分:1)

我会使用GregorianCalendar.isLeapYear方法

答案 2 :(得分:0)

尝试以下代码,看看它是否有效。我刚刚修改了你的代码并添加了一些额外的条件。

import java.util.Scanner;
public class MyTry
{
    public static void main(String[] args){  
    Scanner S = new Scanner(System.in);
    System.out.println("Please enter a year");
    int year = S.nextInt();
    if (year > 1582){

    if (((year%4)== 0) && ((year%100)==0) && ((year%400)==0)) {
        System.out.print("That year was a leap year");
    }
    else if (((year%4)== 0) && ((year%100)==0) && ((year%400)!=0)){
        System.out.println("This year was not a leap year");
    }
    else if ((year%4)== 0){
        System.out.print("This year was a leap year");
    }
    else 
        System.out.print("This year was not a leap year");
    }
    else 
       System.out.print ("Please enter a year after 1582");
    }
}

答案 3 :(得分:0)

闰年除以4而不是100,或除以400。

以下是检查闰年的方法:

import java.util.Scanner;

public class Leap {
    public static void main (String[] args) {
        Scanner s = new Scanner(System.in);
        int year;
        boolean check;

        // Keep taking entries as long as the
        // inserted value is not valid (less than 1582)
        do {
            System.out.print("Input year (greater than 1582): ");
            year = s.nextInt();
        } while (year < 1582);

        //A Leap year is a year that is divided by 4 and not by 100,
        //or divided by 400.
        check = (year % 400 == 0) || (year % 4 == 0 && (year % 100 != 0));

        // Print out the result
        System.out.format("Is year %d a leap year: %b\n", year, check);
    }
}