代码概要
根据输入月份判断该月份的天数;
利用数组进行月份匹配,2月份单独输出天数判断结果。
代码核心
主要利用整型一维数组和for循环语句实现根据输入月份判断天数。
代码部分
Java代码
3. import java.util.Scanner;
4.
5. public class judge_month {
6. public static void main(String[] args) {
7. Scanner input = new Scanner(System.in);
8. System.out.println("请输入要判断天数的月份(1~12):");
9. int m = input.nextInt();
10. int[] array_day31 = new int[]{1, 3, 5, 7, 8, 10, 12};
11. int[] array_day30 = new int[]{4, 6, 9, 11};
12. if(m==2){
13. System.out.println("2月份有29天或28天,需要根据年份进一步判断。");
14. } else {
15. for (int element : array_day31) {
16. if (element == m) {
17. System.out.println(m + "月份有31天。");
18. }
19. }
20. for (int element : array_day30) {
21. if (element == m) {
22. System.out.println(m + "月份有30天。");
23. }
24. }
25. }
26. }
27. }
结果示例
结果分析:
根据用户输入月份“8”,输出“8月份有31天”,可知程序运行结果正确。此外,由于2月份较为特殊,因此当用户想要通过该程序得到2月份包含的天数时,输出“2月份有29天或28天,需要根据年份进一步判断。”。