简体   繁体   中英

NullPointer on Clip after Clip was initialized in for loop

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM