-6

我需要制作一个程序(使用 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

4 回答 4

2

在这一行

if ((year / 400)= 0) {

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

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

此外,您需要涵盖诸如 1900 年(可被 100 但不能被400 整除)之类的情况,这些情况不是闰年。

于 2013-07-02T00:23:25.240 回答
1

我会使用GregorianCalendar.isLeapYear方法

于 2013-07-02T03:43:07.387 回答
0

A leap year is divided by 4 and not by 100, or divided by 400.

Here is how you can check a Leap year:

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);
    }
}
于 2014-09-24T15:03:18.490 回答
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");
    }
}
于 2013-07-02T01:31:21.193 回答