链接提交百度站长平台,布吉做棋牌网站建设哪家公司便宜,做网站一定要公司备案吗,怎么写网站规划方案文章目录一、练习题目二、使用 switch 语句实现代码三、将代码改写回 if else 的选择结构一、练习题目 编写 Java 程序#xff0c;输入年份和月份#xff0c;使用 switch 结构计算对应月份的天数。 月份为 1、3、5、7、8、10、12 时#xff0c;天数为 31 天。 月份为 4、6、…
文章目录一、练习题目二、使用 switch 语句实现代码三、将代码改写回 if else 的选择结构一、练习题目 编写 Java 程序输入年份和月份使用 switch 结构计算对应月份的天数。 月份为 1、3、5、7、8、10、12 时天数为 31 天。 月份为 4、6、9、11 时天数为 30 天。 月份为 2 时若为闰年天数为 29 天否则天数为 28 天。 要求实现程序如下图所示 二、使用 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 月时如下图所示 说明System.exit(status)是在System类中定义的调用这个方法可以终止程序。
参数status为 0 表示程序正常结束。一个非 0 的状态代码表示非正常结束。
例如我们输入月份为 13 时程序终止并输出报错信息如下图所示 三、将代码改写回 if else 的选择结构
我们将代码改写回 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 天);}
}输出结果无误如下图所示 我是白鹿一个不懈奋斗的程序猿。望本文能对你有所裨益欢迎大家的一键三连若有其他问题、建议或者补充可以留言在文章下方感谢大家的支持