功能不起作用/改进程序

时间:2015-07-02 12:12:43

标签: java

iframe

1 个答案:

答案 0 :(得分:1)

通过一些小修补程序,您的程序可以正常工作。 下次问一个特定的问题(不仅仅是#34;这不工作")。

如评论中所述,您需要做一些小的调整:

validDate(...)中的

调用daysInMonth方法并检查当天的结果。并且ifLeapYear方法应该在daysInMonth方法中调用(而不是在代码中使用相同的逻辑两次)

public class Program {

public static final int MONTH_THIRTY = 30;
public static final int OTHER_MONTH = 31;
public static final int FEB = 28;
public static final int LEAP_FEB = 29;
public static final int MONTHS = 12;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter date (day/month/year)");
    String nextLine = sc.nextLine();
    String[] split = nextLine.split("/");
    int day = Integer.valueOf(split[0]);
    int month = Integer.valueOf(split[1]);
    int year = Integer.valueOf(split[2]);
    System.out.println("day:" + day + " month: " + month + " year: " + year);
    validDate(day, month, year);

}

public static void validDate(int date, int month, int year) {
    if ((year > 0) && (month > 0 && month <= 12) && (date > 0 && date <= daysinMonth(month, year))) {
        System.out.println("Date is valid");
    } else {
        System.out.println("Date is not valid");
    }
}

public static int daysinMonth(int month, int year) {

    switch (month) {
    case 2:
        return isLeapYear(year) ? LEAP_FEB : FEB;
    case 4:
    case 6:
    case 9:
    case 11:
        return MONTH_THIRTY;
    default:
        return OTHER_MONTH;
    }

}

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