用java编写:输入任意年份和月份,输出对应月份的天数。

用switch case....

用 java编写:输入任意年份和月份,输出对应月份的天数,首先判断输入年份是否是闰年,然后使用switch 方法判断月份,判断代码如下:

public class GetDays { 

public static int getDays(int year, int month) {
int days = 0;
boolean isLeapYear = false;
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
System.out.println("这一年是闰年");
isLeapYear = true;
} else {
System.out.println("这一年不是闰年");
isLeapYear = false;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
if (isLeapYear) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
System.out.println("error!!!");
break;
}
return days;
}
}

扩展资料

在java 语言中switch 语法的使用规则为:

1、switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。

2、switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。

3、case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。

3、当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。

参考资料:百度百科—switch

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-30
import java.util.*;public class DateTest2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
int day = 0;

switch (month) {
case 1:;case 3: ; case 5: ; case 7: ; case 8: ; case 10: ; case 12 : day = 31; break;
case 4:;case 6: ; case 9: ; case 11: day = 30; break;
case 2: day = year % 4 == 0 ? 29 : 28;
default : break;
}

System.out.println(year + "年" + month + "月一共有" + day + "天");
}
} //已经测试过了,是对的本回答被网友采纳
第2个回答  2020-06-19
import java.util.Scanner;
public class test04 {
public static void main(String[] args) {
System.out.println("请输入一个月份:");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
switch(a)
{
case 2:System.out.println(28);break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:System.out.println(31);break;
case 4:
case 6:
case 9:
case 11:System.out.println(30);break;
default:System.out.println("输入错误!");
a = sc.nextInt();
}
}
}
第3个回答  2013-08-30
楼上的写的没什么问题,可是你的算法中有一个失误,那就是年份为100的倍数时,要能够整除400才能是29天,所以 “”“case 2: day = year % 4 == 0 ? 29 : 28;”“” 这一句要改为 """ case 2 : day = year % 100==0 ? year % 400== 0 ? 29 : 28 : year % 4 == 0 ? 29 : 28;""本回答被网友采纳