重复闰年代码

时间:2016-01-29 16:33:00

标签: java repeat

我已经知道如何检查闰年,如下:

import java.util.*;

public class LeapYear {
    public static void main(String[] args) {
        int year;
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter year: ");
            year = scan.nextInt();

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

但现在我想重复这段代码。我以前看过重复代码片段,我几乎可以使用任何代码片段,但是这个给我带来了麻烦。

import java.util.Scanner;

public class LeapUpgrade
{

    public static void main(String[] args)

    {
        String another = "y";
        int year;

        Scanner scan = new Scanner(System.in);

        while (another.equalsIgnoreCase("y")) 
        {
            System.out.println("Enter year: ");
            year = scan.nextInt();

            if ((year % 4 == 0) && year % 100 != 0) 
            {

                System.out.println(year + " is a leap year.");
                System.out.print("test another (y/n)? ");
                another = scan.nextLine();

            }

            else if ((year % 4 == 0) && (year % 100 == 0)
                    && (year % 400 == 0)) 
            {

                System.out.println(year + " is a leap year.");
                System.out.print("test another (y/n)? ");
                another = scan.nextLine();

            } 

            else 

            {

                System.out.println(year + " is not a leap year.");
                System.out.print("test another (y/n)? ");
                another = scan.nextLine();
            }

        }
    }
}

我在这里做错了什么? 在此先感谢您的帮助,不要评判。

2 个答案:

答案 0 :(得分:4)

为避免重复,只需将代码行封装在方法

public static boolean isLeapYear(int year){
    return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0);
}

然后您可以像这样调用它

if(LeapYear.isLeapYear(year)){
 System.out.println("Leap year");
}else{
 System.out.println("Not a leap year");
}

答案 1 :(得分:1)

编辑:请参阅Rohan的回答。为了模块化和代码的清洁/可读性,它更好。

当你想多次做某事时,你通常只需要一个循环。作为提示,您的循环应该包含代码的这一部分:

year = scan.nextInt();

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

我会给你留下循环和条件的类型。