You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java月份天数查询程序问题:错误月份输入未触发提示

问题分析与解决:非法月份输入未触发错误提示

问题根源

你的代码存在一个致命语法错误:else if (month.equals("Feb"))这一行末尾多了一个分号;。这个分号会将该条件分支转化为空语句,意味着当条件满足时不会执行任何逻辑,而后续的System.out.print(((leapYear) ? 29 : 28) + " days");会变成独立执行的代码——无论输入的月份是否为Feb,这行代码都会无条件运行。

这直接导致:所有不匹配前两个if/else if条件的输入(包括jan这类非法月份),都会先执行这句输出天数的代码,永远走不到最后的else错误提示分支。

修正后的代码

只需删除else if (month.equals("Feb"))后面的分号即可,完整代码如下:

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a year and
        // the first three letter of a month name
        System.out.print("Enter a year: ");
        int year = input.nextInt();
        System.out.print("Enter a month: ");
        String month = input.next();

        // Test for leap year
        boolean leapYear = 
            ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);

        // Display the number of day in the month
        System.out.print(month + " " + year + " has ");
        
        if ( month.equals("Jan") || month.equals("Mar") || 
              month.equals("May") || month.equals("Jul") ||
              month.equals("Aug") || month.equals("Oct") ||
              month.equals("Dec"))
            System.out.print(31 + " days");
        else if (month.equals("Apr") || month.equals("Jun") || 
            month.equals("Sep") || month.equals("Nov"))
            System.out.print(30 + " days");
        else if (month.equals("Feb"))
            System.out.print(((leapYear) ? 29 : 28) + " days"); 
        else 
           System.out.print(month + " is not a correct month name");
    }
}

额外优化建议(可选)

如果希望程序兼容大小写输入(比如接受jan、JAN等格式),可以将字符串比较替换为equalsIgnoreCase方法,示例:

if (month.equalsIgnoreCase("Jan") || month.equalsIgnoreCase("Mar") ...)

内容的提问来源于stack exchange,提问作者Boiz734

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:55:06