这个问题已经在这里有了答案:




已关闭8年。






这是家庭作业,我已经获得了成绩,但是我没有在代码中实现leap年。这是一个简单的程序,可以根据用户输入显示一个月内的数字。我唯一不知道的是一种实现implement年的方法,该writing年将在2月获得29天而不是28天,而不编写多个if语句。当然有更简单的方法吗?这是代码:

//Displays number of days in a month

package chapter_3;

import java.util.Scanner;


public class Chapter_3 {

    public static void main(String[] args) {
        System.out.println("This program will calculate \n"
                + "the number of days in a month based upon \n"
                + "your input, when prompted please enter \n"
                + "the numerical value of the month you would like\n"
                + "to view including the year. Example: if you would like\n"
                + "to view March enter 3 2011 and so on.");

        Scanner input = new Scanner(System.in);

        //Prompt user for month and year
        System.out.print("Please enter the month and year: ");
        int month = input.nextInt();
        int year = input.nextInt();

        if (month == 1) {
            System.out.println("January " + year + " has 31 days");
        }
        else if (month == 2) {
            System.out.println("February " + year + " has 28 days");
        }
        else if (month == 3) {
            System.out.println("March " + year + " has 31 days");
        }
        else if (month == 4) {
            System.out.println("April " + year + " has 30 days");
        }
        else if (month == 5) {
            System.out.println("May " + year + " has 31 days");
        }
        else if (month == 6) {
            System.out.println("June " + year + " has 30 days");
        }
        else if (month == 7) {
            System.out.println("July " + year + " has 31 days");
        }
        else if (month == 8) {
            System.out.println("August " + year + " has 31 days");
        }
        else if (month == 9) {
            System.out.println("September " + year + " has 30 days");
         }
        else if (month == 10) {
            System.out.println("October " + year + " has 30 days");
        }
        else if (month == 11) {
            System.out.println("November " + year + " has 30 days");
        }
        else if (month == 12) {
            System.out.println("December " + year + " has 31 days");
         }
        else {
            System.out.println("Please enter the numerical value "
                + "of the month you would like to view");
        }
    }
}

最佳答案

如果使用 GregorianCalendar ,则可以执行以下操作


GregorianCalendar cal = new GregorianCalendar();

if(cal.isLeapYear(year))
{
    System.out.print("Given year is leap year.");
}
else
{
    System.out.print("Given year is not leap year.");
}

10-06 10:20