java - 遍历列表并减去前面的元素会产生不需要的结果
问题描述
我正在尝试用 Java 创建一个 MIDI 阅读程序。目标是保存 MIDI 文件中的音符和音符的拍号,使用每个音符的节拍并减去它们以找到值的差异,然后将它们转换为相应的时间值。
我的程序的示例输出将是:
Tick at @27576
Channel: 2
Note = AS1 key = 34
Tick at @27600
Channel: 2
Note = AS1 key = 34
Tick at @27624
Channel: 2
Note = AS1 key = 34
Tick at @29952
//and so on
然后刻度值将被插入到一个名为的 ArrayListnoteTimings
中,而音符值将被插入到一个名为的 ArrayList 中noteKeyValues
因此,在示例输出中 -noteTimings
将具有以下值: [27576, 27600, 27624, 29952]
现在,我想要完成的是用前一个元素减去最后一个元素(例如 29952 - 27624),然后将该值插入到新的 ArrayList 中。这将一直持续到每个元素都在 for 循环中被迭代。
我的for循环:
ArrayList<Integer> newNoteTimings = new ArrayList<>();
for (int i = noteTimings.size() - 1; i >= 1; i--) {
for (int j = i - 1; j >= 0; j--) {
newNoteTimings.add((noteTimings.get(i) - noteTimings.get(j)));
}
}
System.out.println(newNoteTimings);
预期成绩:
2328
24
24
实际结果:
2328
2352
2376
有什么我忽略的吗?任何帮助,将不胜感激!
解决方案
您可以反转列表并从头开始执行减法,例如:
List<Integer> list = new ArrayList<>();
list.add(27576);
list.add(27600);
list.add(27624);
list.add(29952);
//Reverse the list
Collections.reverse(list);
List<Integer> result = new ArrayList<>();
for(int i=0 ; i<list.size() - 1 ; i++) {
result.add(list.get(i) - list.get(i+1));
}
System.out.println(result);
推荐阅读
- apache - 设置 zend 骨架应用程序
- scala - toIterable 的目的
- javascript - 为什么javascript找不到元素?
- autohotkey - 如何重新映射 3 个小键盘键以在自动热键中运行控制面板?
- spring-boot - 即使单元测试成功,Maven 构建也会失败
- angular - 在 angular.json 文件中设置 optimization=true 时无法下载文件
- json - 从 JSON 响应中删除 EclipseLink 特定字段
- c - 将字符串从 Rust 传递到 C 会导致段错误或错误
- python - 如何修复打印在带有随机库的 python 中不起作用
- ansible - 使用 Google-Authenticator 时的 Ansible SSH 连接