I have some code here and it's confusing me; I'm trying to figure out why I'm getting a null pointer exception. I set up a for-each-loop to initialize each clip. If I initialize each one by itself, it works just fine, and the clips play.
musicArr[0]=menuMusic;
soundArr[0]=shotSound;
try
{
for(Clip c:musicArr)c=AudioSystem.getClip();
for(Clip c:soundArr)c=AudioSystem.getClip();
menuMusic.open(AudioSystem.getAudioInputStream(new File("menuMusic.wav")));
shotSound.open(AudioSystem.getAudioInputStream(new File("shot.wav")));
}catch(LineUnavailableException|UnsupportedAudioFileException|IOException ex){ex.printStackTrace();}
This is going to pose as a nuisance later when I add more sound clips and music clips to the program. Anyone know of a cause for this?
Because of the way for-each loops are constructed, you cannot assign a reference to the item being looped for inside the loop. You can change the object's state, yes, but you can't assign a new object to the looping item. The solution is to change your for-each loop to a traditional for loop.
For example, change:
for(Clip c:musicArr)c=AudioSystem.getClip();
to
// if musicArr is an array and not an ArrayList
for (int i = 0; i < musicArr.length; i++) {
musicArr[i] = AudioSystem.getClip();
}
As a side note, avoid compressing your calls onto one line as you're doing. There's no cost for smart use of white space, so use it smartly to aid in the readability (and thus "debug-ability") of your code.