怎么编写Java程序使用switch结构计算对应月份的天数

发布时间:2021-10-18 11:50:46 作者:iii
来源:亿速云 阅读:251

本篇内容主要讲解“怎么编写Java程序使用switch结构计算对应月份的天数”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么编写Java程序使用switch结构计算对应月份的天数”吧!

有题如下:

编写 Java 程序,输入年份和月份,使用 switch 结构计算对应月份的天数。
月份为 1、3、5、7、8、10、12 时,天数为 31 天。
月份为 4、6、9、11 时,天数为 30 天。
月份为 2 时,若为闰年,天数为 29 天,否则,天数为 28 天。

实现如下程序:
怎么编写Java程序使用switch结构计算对应月份的天数

一、使用 switch 语句实现代码

package rjxy2019_java_demo;import java.util.Scanner;public class SwitchWithDays {   public static void main(String[] args) {   
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter a year:");int year = input.nextInt();
		System.out.println("Please enter a month:");int month = input.nextInt();int day = 0;boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 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:if(isLeapYear == true) day = 29;else day = 28;break;default:System.out.println("Error:invalid input");
		System.exit(1);}
		System.out.println(year + "年" + month + "月一共" + day + "天");}}

验证,当输入为 2009 年 2 月时:

怎么编写Java程序使用switch结构计算对应月份的天数

二、将代码改写回 if else 的选择结构

package rjxy2019_java_demo;import java.util.Scanner;public class IfElseWithDays {   public static void main(String[] args) {   
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter a year:");int year = input.nextInt();
		System.out.println("Please enter a month:");int month = input.nextInt();int day = 0;boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month ==12) day = 31;else{   if(month == 4 || month == 6 || month == 9 || month == 11) day = 30;else {   if(month == 2) {   if(isLeapYear == true) day = 29;else day = 28;}else {   
					System.out.println("Error:invalid input");
					System.exit(1);}}}
		System.out.println(year + "年" + month + "月一共" + day + "天");}}

到此,相信大家对“怎么编写Java程序使用switch结构计算对应月份的天数”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. python分支结构(无switch结构)
  2. switch 语句输出该整数对应的星期几

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java switch

上一篇:ButterKnife 8.5.1怎么用

下一篇:oppo手机如何使用应用沙盒动态修改sdk数据

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》