一个月中的天数

时间:2018-10-07 10:03:16

标签: java

我一直在尝试在实践中解决此问题,由于某种原因,它将无法工作。它应该是采用int(month)并返回其中天数的方法。例如,daysInMonth(3)= 31,因为三月份有31天。 这是我的代码

public static void main(String[] args){
    daysInMonth();
}

public static void daysInMonth (int month){
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to number of days in a month\nChoose a month ( Jan - 1, Feb -2,...): ");
    int month = input.nextInt();
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        System.out.println("30 days");
    } else if ( month == 2){
        System.out.println("28 days");
    } else {
        System.out.println("31 days");
    }   
}

2 个答案:

答案 0 :(得分:1)

我认为参数不是必需的-您正在请求方法中的输入。 这样声明您的方法:

public static void daysInMonth ()

或在调用方法时完全删除输入并输入参数。 像这样:

public static void main(String[] args){
    daysInMonth(3);
}

public static void daysInMonth (int month){
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        System.out.println("30 days");
    } else if ( month == 2){
        System.out.println("28 days");
    } else {
        System.out.println("31 days");
    }   
}

答案 1 :(得分:0)

在java8中,时间api效率更高。像这样使用;

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to number of days in a month\nChoose a month ( Jan - 1, Feb - 2,...): ");
    int month = input.nextInt();
    daysInMonth(month);
}

public static void daysInMonth(int month) {
    YearMonth yearMonthObject = YearMonth.of(LocalDateTime.now().getYear(), month);
    System.out.println(yearMonthObject.lengthOfMonth() + " days");
}
相关问题