【问题标题】:How do I Create a Loop That Will Return The Days on the Month for my Code?如何创建一个循环来返回我的代码的月份日期?
【发布时间】:2021-11-26 01:40:44
【问题描述】:
public class Array {
    public static void main(String args[]) {
       int[] daysInMonth = new int[31];
       for (int i = 0; i < 31; i++) {
           System.out.println("Day of the month: " + daysInMonth[i]);
       }
    }
}

我知道我可以硬编码每个月的每一天的值。我可以这样做:daysInMonth[0] = 1;对于当月的所有值,但为了提高效率想使用循环来代替。我将如何创建一个循环来输出“每月的天数:1,每月的天数:2,等等?”

【问题讨论】:

  • 所以您只想将值1 输出到31?听起来你可以只输出i + 1 的值,然后daysInMonth 数组不会增加任何值。
  • 如果可以打印i+1,为什么还要使用数组?

标签: java arrays loops


【解决方案1】:

如果我理解正确,您不需要数组,只需在输出中写入i 并像这样更改循环参数

for (int i = 1; i < 32; i++) {
    System.out.println("Day of the month: " + i);
}

【讨论】:

  • 这最终奏效了。感谢您的帮助!
【解决方案2】:

您可以在循环中使用数组长度,因为月份有不同的长度,并打印 i 而不是数组的索引 [i]。

 int[] daysInMonth = new int[31];
   for (int i = 0; i <= daysInMonth.length-1; i++) {
       System.out.println("Day of the month: " + (i+1));
   }

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2021-11-27
    • 2020-08-13
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2020-11-28
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多