RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
怎么编写Java程序使用switch结构计算对应月份的天数

本篇内容主要讲解“怎么编写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结构计算对应月份的天数”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


分享名称:怎么编写Java程序使用switch结构计算对应月份的天数
地址分享:http://scyingshan.cn/article/jogesc.html