【问题标题】:how to change an element in an array that is defined as a method?如何更改定义为方法的数组中的元素?
【发布时间】:2022-01-21 11:38:38
【问题描述】:
private static int[] daysInMonth = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 };

我正在寻找一种方法,如果 year % 4 == 0 然后是 daysInMonth[1] = 29

【问题讨论】:

  • if (year % 4 == 0) { daysInMonth[1] = 29; },如果这不是你想要的,那么你需要澄清你在问什么
  • 1) 将数组定义为方法是什么意思? 2) 假设闰年由year % 4 == 0 定义是不完全正确的。 3) 为什么您需要更改数组中的值?这意味着对于其他“调用”,您必须检查/恢复 28 天。

标签: java arrays if-statement


【解决方案1】:

虽然问题不是很清楚,但我会尝试回答。

您似乎要问的是,当您访问 daysInMonth[1] 时,您需要它根据您使用的年份是动态的。

如果您希望使用 daysInMonth[1],那么不使用 lamdas 或方法引用作为数组而不是整数是不可能的。

我建议您通过访问器方法访问值,如下所示:

public int daysOfMonth(int year, int month) {
  if (month == 1 && year % 4 == 0) {
    return 29;
  }
  return daysInMonth[month];
}

【讨论】:

  • year % 4 == 0 在儒略历中检测闰年是正确的,而公历已经使用了一段时间。此方法也 always 返回二月份的天数 :)
  • 更正了:P
【解决方案2】:

您可以检查是否是闰年。如果是,则 2 月有 29 天。

 private static int[] daysInMonth = {31 , LocalDate.now().isLeapYear() ? 29:28 ,
                                    31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多