java - Why is my code causing an infinite loop? -
i'm working on method creates playlist music library. thought asks minimum rating songs , minimum runtime playlist , produces random list of songs fit criteria. if there not plenty songs of minimum rating, reduces rating 1 , looks songs meet requirement. (so if specified playlist should have 60 mins of 5 star songs, don't have enough, tries fill rest of time 4 star songs instead.)
however, if library contains no 5 star songs, infinite loop caused in code. (or assume so, anyway, test programme doesn't stop running) why be?
public playlist createplaylist(int minrating, int minduration) { minduration = minduration * 60; arraylist<track> shuffledlist = tracklist; playlist playlist = new playlist(); collections.shuffle(shuffledlist); int playlistduration = 0; while (playlistduration <= minduration) { (track track : shuffledlist) { if (track.getrating() >= minrating && !playlist.contains(track)) { playlist.add(track); playlistduration += track.getlength(); } if (playlistduration >= minduration) { break; } } minrating--; } playlist.randomise(); homecoming playlist;
since playlistduration
updated conditionally, there many reasons loop become infinite. example, if shuffledlist
empty, playlistduration
remain zero, outer loop infinite.
you can avoid if adjust minduration
total duration of shuffledlist
before entering loop:
minduration = math.min(minduration, shuffledlist.sum(t => t.getlength()));
in plain english language means "i cannot inquire minimum duration of more total duration of shuffledlist
".
you should alter status of while
loop strict "less than", because otherwise infinite loop remain when shuffledlist
empty.
while (playlistduration < minduration) { ... }
java infinite-loop
No comments:
Post a Comment