Removing while iterating issues in java -


i want implement method attack works this: every warrior troop attacks warrior chosen randomly troop. if attacked warrior dies must removed troop. method tried error random number:

 java.lang.illegalargumentexception: n must positive 

the troop list <creature> warriors; think not doing remove correctly, because otherwise should not have error.

public void atac(troop opponenttroop){         for(creature f : warriors){             creature c = getopponent(opponenttroop);             f.atac(c);             listiterator<creature> iterator = opponenttroop.warriors.listiterator();             while(iterator.hasnext()){                 c = iterator.next();                 if(c.isdead()){                     iterator.remove();                                   }             }             }            }   private creature getopponent(troop opponent){         int x = rand.getrandomarrayindex(opponent.warriors.size());         return opponent.warriors.get(x); } 

removing entry invalidates iterator. need save it, this:

while(iterator.hasnext()) {     c = iterator.next();     if(c.isdead()) {         // make temporary iterator         listiterator<creature> todelete= c;         // step regular 1         c = iterator.next();         // remove         todelete.remove();                       } }    

also, make sure int x = rand.getrandomarrayindex(opponent.warriors.size()); never goes beyond last index (which number of entries minus one.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -