【问题标题】:Java or SQL add a missing months in arrayJava 或 SQL 在数组中添加缺失的月份
【发布时间】:2017-07-23 15:20:03
【问题描述】:

亲爱的同事们,美好的一天

你能帮帮我吗?我找不到决定。我从 MySQL 得到的数组看起来像这样(数量和月份):

[2, 07.16, 3, 08.16, 2, 10.16, 1, 11.16, 1, 12.16, 1, 01.17]

我需要添加 0 和在此期间错过的月份。对于这个数组应该在08.16之后加上0和09.16,所以变成如下样子:

[2, 07.16, 3, 08.16, 0, 09.16, 2, 10.16, 1, 11.16, 1, 12.16, 1, 01.17]

将不胜感激任何建议!

PS。我试图在 Java 中做这样的事情:

for (int i = objArrayOfCalulatedRisks.length; i > 3; i = i - 2) {
            String dayMonthAndYear = objArrayOfCalulatedRisks[i].toString();
            StringBuilder sb = new StringBuilder();
            sb.append(dayMonthAndYear.charAt(3));
            sb.append(dayMonthAndYear.charAt(4));
            String rightMonth = sb.toString();
            String dayMonthAndYear2 = objArrayOfCalulatedRisks[i-2].toString();
            StringBuilder sb2 = new StringBuilder();
            sb2.append(dayMonthAndYear.charAt(3));
            sb2.append(dayMonthAndYear.charAt(4));
            String leftMonth = sb2.toString();
            int rightM = Integer.parseInt(rightMonth);
            int leftM = Integer.parseInt(leftMonth);        

            if (leftM + 1 != rightM) {

            }         

【问题讨论】:

    标签: java mysql arrays calendar missing-data


    【解决方案1】:

    首先,您应该将输入数组解析为适当的内容,例如 NavigabeMap<YearMonth, Integer>。然后您可以计算最低和最高 YearMonths 之间的月份并填充您的结果数组。

    String[] objs = { "2", "07.16", "3", "08.16", "2", "10.16", 
                      "1", "11.16", "1", "12.16", "1", "01.17" };
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yy");
    NavigableMap<YearMonth, Integer> quantities = new TreeMap<>();
    for (int i = 0; i < objs.length; i += 2) {
      quantities.put(YearMonth.from(formatter.parse(objs[i + 1])), Integer.valueOf(objs[i]));
    }
    String[] result;
    if (quantities.isEmpty()) {
      result = new String[0];
    } else {
      YearMonth lowest = quantities.firstKey();
      YearMonth highest = quantities.lastKey();
      int months = (int) ChronoUnit.MONTHS.between(lowest, highest) + 1;
      result = new String[months * 2];
      for (int i = 0; i < months; i++) {
        YearMonth ym = lowest.plusMonths(i);
        result[i * 2] = quantities.getOrDefault(ym, 0).toString();
        result[i * 2 + 1] = formatter.format(ym);
      }
    }
    System.out.println(Arrays.toString(result));
    

    输出:

    [2, 07.16, 3, 08.16, 0, 09.16, 2, 10.16, 1, 11.16, 1, 12.16, 1, 01.17]

    如果您正在寻找 MySQL 解决方案,那么您应该使用number table

    【讨论】:

    • 非常感谢!我将使用 Java 决定,它更适合我的任务。
    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多