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

如何用Java编写循环批量打印各月份及对应每月天数

优化方案

你可以通过索引匹配的for循环同时遍历两个对应数组,无需重复编写打印语句,修改后的完整代码如下:

public class Array {

    public static void main(String args[]) {
        String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        // 新增for循环遍历所有下标
        for (int i = 0; i < months.length; i++) {
            System.out.println("There are a total of " + daysInMonth[i] + " days in the month of " + months[i] + ".");
        }
    }

}
逻辑说明
  • 两个数组的下标是一一对应的,索引0对应1月,索引1对应2月,以此类推直到索引11对应12月
  • 循环次数和months数组的长度绑定,即使后续数组元素有增减也不需要手动修改循环边界
  • 如果需要适配闰年2月29天的场景,可在循环内新增对2月的判断逻辑,调整daysInMonth[1]的取值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:48:04