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

用switchcase....... 用switch case.... 展开
 我来答
八零后电影院
高粉答主

2018-12-08 · 说的都是干货,快来关注
知道小有建树答主
回答量:330
采纳率:100%
帮助的人:8.9万
展开全部

用 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

匿名用户
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 + "天");
}
} //已经测试过了,是对的
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
kkkmmm
2020-06-19
知道答主
回答量:2
采纳率:0%
帮助的人:1131
展开全部
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();
}
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
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;""
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式