【问题标题】:How Would I Create a Loop to Display the Months and Days in Each Month?如何创建一个循环来显示每个月的月份和日期?
【发布时间】:2021-11-26 03:14:40
【问题描述】:
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 };
        System.out.println("There are a total of " + daysInMonth[0] + " days in the month of " + months[0] + ".");
    }

}

我不是每个月打印到控制台 12 次不同的时间,而是如何提高我的代码效率并创建一个循环来打印出数组中的每个元素?

【问题讨论】:

    标签: java arrays loops


    【解决方案1】:

    尝试以下操作:

    for (int i = 0; i < 12; i++) {
        System.out.println("There are a total of " + daysInMonth[i] + " days in the month of " + months[i] + ".");
    }
    

    【讨论】:

    • 谢谢!实际上,我之前的代码中有以下行: for (int i = 0; i
    • 没错,这就是循环在这里所做的。
    【解决方案2】:

    answer by semicolon 是正确的,您应该接受。我写这个答案是为了向您介绍java.time API。

    import java.time.Month;
    import java.time.format.TextStyle;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i <= 12; i++) {
                Month month = Month.of(i);
                System.out.println(month.getDisplayName(TextStyle.FULL, Locale.ENGLISH) + " has a maximum of "
                        + month.maxLength() + " days.");
            }
        }
    }
    

    输出:

    January has a maximum of 31 days.
    February has a maximum of 29 days.
    March has a maximum of 31 days.
    ...
    

    ONLINE DEMO

    通过 Trail: Date Time 了解有关 modern Date-Time API* 的更多信息。

    【讨论】:

      【解决方案3】:

      你可以创建一个 Map 然后遍历它。

      final Map<String, Integer> months = new HashMap<>();
      months.put("January", 31);
      months.put("February", 28);
      ...
      months.forEach((k, v) -> System.out.println("There are a total of " + v + " days in the month of " + k + "."));
      

      【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2020-06-07
      • 2020-11-29
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多