So I’m making a MIDI program in Java. I’ve got a buffer and this is the thread that I’m using to take the message from the buffer, and pass them into a window class which will display them.
I keep getting an ArrayIndexOutOfBounds error whenever I send a message that only has two parameters. I’ve tried using a separate Array as well as an if statement, but neither seems to work. The error says it has something to do with the if statement/the third parameter variable.
I’ve used a switch statement as well as masking to determine which type of message is being received, but the ones with two parameters instead of three throw an error and it has something to do with the arrays and the number of parameters.
public class DisplayThread extends Thread {
Buffer bufferObj;
MidiMonitorWindow window = new MidiMonitorWindow("MIDI Devices");
DisplayThread(Buffer bufferObj) {
this.bufferObj = bufferObj;
}
public void run() {
while (true) {
byte[] getMessages = bufferObj.get();
if (getMessages != null) {
int statusValue = getMessages[0] & 0xF0;
int [] paramArray = new int[3];
paramArray[0] = getMessages [0] & 0xFF;
paramArray[1] = getMessages [1] & 0xFF;
if (getMessages[2] != 0){
paramArray[2] = getMessages [2] & 0xFF;
}
switch (statusValue) {
case NOTE_OFF:
System.out.println("Note Off");
window.showNoteOff(paramArray[0], paramArray[1], paramArray[2]);
break;
case NOTE_ON:
System.out.println("Note On");
window.showNoteOn(paramArray[0], paramArray[1], paramArray[2]);
break;
case POLY_PRESSURE:
System.out.println("Poly Pressure");
window.showPolyKeyPressure(paramArray[0], paramArray[1], paramArray[2]);
break;
case CONTROL_CHANGE:
System.out.println("Control Change");
window.showControlChange(paramArray[0], paramArray[1], paramArray[2]);
break;
case PROGRAM_CHANGE:
System.out.println("Program Change");
window.showProgramChange(paramArray[0], paramArray[1]);
break;
case CHANNEL_PRESSURE:
System.out.println("Channel Pressure");
window.showChannelPressure(paramArray[0], paramArray[1]);
break;
case PITCH_BEND:
System.out.println("Pitch Bend");
window.showPitchBend(paramArray[0], paramArray[1], paramArray[2]);
break;
default:
System.out.println("System Message");
window.showSystemExclusive();
break;
}
}
}
}
}
Any advice you could offer would be most helpful!
If the purpose of your
if (getMessages[2] != 0)there is to check whether there is a3rd elementin your array or not, then that will not work.See this code of array creation: –
Now,
bufferObj.get()will only give you2 elementarray, if there are only 2 elements. So, the size of the array is not defined explicitly. It depends upon whatbufferObj.get()returns. So, there will not be any2nd indexin your array, if the number of element is just2. And that is why you are gettingArrayIndexOutOfBoundsexception in case of2 elements.You can check for the
3rd elementexistence by checking the length of the array obtained: –