首页 > 解决方案 > 遍历列表并减去前面的元素会产生不需要的结果

问题描述

我正在尝试用 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

有什么我忽略的吗?任何帮助,将不胜感激!

标签: javafor-loopiterationmidi

解决方案


您可以反转列表并从头开始执行减法,例如:

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);

推荐阅读