String s="2016,5,2016,7,2017,7,2017,8,2019,7,2019,6 * 计算年收入: * 输出结果为2016:12(5+7)2017:15(7+8)·····
时间: 2023-09-01 09:13:38 浏览: 29
可以使用 HashMap 来记录每一年的收入,将每一年的收入累加起来即可。以下是示例代码:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "2016,5,2016,7,2017,7,2017,8,2019,7,2019,6";
String[] arr = s.split(",");
Map<Integer, Integer> map = new HashMap<>();
int i = 0;
while (i < arr.length) {
int year = Integer.parseInt(arr[i]);
int income = Integer.parseInt(arr[i+1]);
map.put(year, map.getOrDefault(year, 0) + income);
i += 2;
}
for (int year : map.keySet()) {
int income = map.get(year);
System.out.println(year + ": " + income);
}
}
}
```
输出结果为:
```
2016: 12
2017: 15
2019: 13
```