2017-03-03 75 views
0

美好的一天,親愛的同事Java或SQL在數組中添加缺失的月份

你能幫助我嗎?我找不到決定。我從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。我tryed做這樣的事情在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) { 

      }   

回答

0

首先,你應該分析你輸入數組到合適的像NavigabeMap<YearMonth, Integer>東西。然後,您可以計算最低和最高的YearMonth之間的月份並填寫結果數組。

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

+0

非常感謝!我將使用Java決策,它更適合我的任務。 –