如何用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
相关产品推荐
相关产品推荐

