遍历列表并减去前面的元素会产生不需要的结果
Looping through list and subtracting preceding elements gives unwanted results
我正在尝试在 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
刻度值将被插入到名为 noteTimings
的 ArrayList 中,音符值将被插入到名为 noteKeyValues
的 ArrayList 中
因此,在示例输出中 - 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);
我正在尝试在 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
刻度值将被插入到名为 noteTimings
的 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);