java编写某年某月有多少天

2024-11-27 16:38:24
推荐回答(5个)
回答1:

import java.util.Scanner;

public class DayOfMonth {
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("请输入年");
int year=s.nextInt();
System.out.println("请输入月");
int month=s.nextInt();
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(year+"年"+month+"月有31天");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println(year+"年"+month+"月有30天");
break;
case 2:
if((year%4 == 0&&year%100 != 0)||year%400 == 0)
System.out.println(year+"年2月有29天");
else
System.out.println(year+"年2月有28天");
break;
}
}
}
这样可以了么?

回答2:

借flyingFish211 的代码,把switch给你添上。
不过flyingFish211的回复是很正确的,多学些类库很有用,使用类库中已存的方法,
比自己写要省事,高效。

import java.util.Calendar;

public class Test {

public static void main(String[] args) {
int year = 1900;// 年份
int month = 2;// 月份

int days = getMonthDays(year, month);
System.out.println(days);
days = getMonthDay(year, 2);
System.out.println(days);

}

private static int getMonthDay(int year, int month) {
int result = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
result = 31;
break;
case 4:
case 6:
case 9:
case 11:
result = 30;
break;
case 2:
result = 28;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
result = 29;
}
break;
}

return result;
}

private static int getMonthDays(int year, int month) {
Calendar cal = Calendar.getInstance();

cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);

return cal.getActualMaximum(Calendar.DATE);
}

}

回答3:

import java.util.Calendar;

public class CalUtil {

public static void main(String[] args) {
int year = 2012;//年份
int month = 2;//月份

int days = getMonthDays(year, month);
System.out.println(days);

}

private static int getMonthDays(int year, int month) {
Calendar cal = Calendar.getInstance();

cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month -1);

return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}

}

---------testing
29

回答4:

public static int getDaysByMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.set(year, month, 0);
return c.getActualMaximum(Calendar.DAY_OF_MONTH);
}

回答5:

e