为什么do-while循环在这个Java程序中没有按预期运行?

时间:2016-03-28 12:19:03

标签: java do-while

我一直在编写一个程序,它将获取一系列音乐文件的名称并播放它们。我成功地做到了这一点,但是,我想要修改一些东西,让它更好一些。我试图让音乐以随机顺序播放,但在整个列表播放之前不重复播放任何歌曲。我几乎能够做到,但我认为我的do-while循环有问题。该程序按预期运行大约八首歌曲,但随后它停止播放音乐,JVM继续运行。我正在使用BlueJ,因为我仍然是AP Comp Sci学生,所以我意识到我可能无法完成这项任务,但任何帮助将不胜感激。我有一个驱动程序,“MusicDriver”,它与另外两个类别“有一个”关系:“MP3”和“音乐”。

我的MP3课程:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;

public class MP3 {
    String filename;
    Player player; 

    public void stopMP3() { if (player != null) player.close(); }

    // play the MP3 file to the sound card
    public void playMP3(String filename) {
    try {
        FileInputStream fis = new FileInputStream(filename);
        BufferedInputStream bis = new BufferedInputStream(fis);
        player = new Player(bis);
    }
    catch (Exception e) {
        System.out.println("Problem playing file " + filename);
        System.out.println(e);
    }

    // run in new thread to play in background
    new Thread() {
        public void run() {
            try { player.play(); }
            catch (Exception e) { System.out.println(e); }
        }
    }.start();
}  
}

我的音乐课程:

import java.util.*;

public class Music{
private ArrayList<String> music;

public Music(){music = new ArrayList<String>();}

public int size(){return music.size();}

public void addSong(String song){music.add(song);}

public String getSong(){return music.get(music.size());}

public String getSong(int num){return music.get(num);}

public void removeSong(String song){
    for(int i = 0; i < music.size(); i++){
        if(music.get(i).equals(song)) {music.remove(i); return;}
    }
}

public String toString(){
    String s = "";
    for(int i = 0; i < music.size(); i++){
        s += music.get(i);
    }
    return s;
}
}

我的MusicDriver课程:

import java.util.*;
import java.io.*;
import javazoom.jl.player.Player;
import java.util.Random;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class MusicDriver{
public static void main(String[] args) throws FileNotFoundException{
    Random r = new Random();
    Scanner s = new Scanner(System.in);
    String line = "";
    int number;

    Music song = new Music();
    song.addSong("1-01-overture.mp3");
    song.addSong("1-03-fortune-teller-2.mp3");
    song.addSong("1-07-prayer.mp3");
    song.addSong("1-08-island-atlas.mp3");
    song.addSong("1-12-warren-report.mp3");
    song.addSong("1-13-avilla-hanya.mp3");
    song.addSong("1-20-war-situation.mp3");
    song.addSong("2-10-fog-of-phantom.mp3");
    song.addSong("2-12-religious-precepts.mp3");
    song.addSong("2-14-box-of-sentiment.mp3");
    song.addSong("3-02-light-everlasting.mp3");
    song.addSong("3-09-viking-spirits.mp3");
    song.addSong("3-12-unsealed.mp3");
    song.addSong("3-16-notice-of-death-reprise-.mp3");
    //14 songs

    ArrayList<Integer> songNums = new ArrayList<Integer>();
    MP3 mp3 = new MP3();
    do{
        if(songNums.size() == song.size()) songNums.clear();

        number = r.nextInt(song.size());
        boolean done = false;
        int counter = 0;
        while(!done){
            for(int i = 0; i < songNums.size(); i++){
                if(number == songNums.get(i).intValue()) {number = r.nextInt(song.size()); counter++;}
            }
            if(counter == 0) done = true;
            else done = false;
        }

        songNums.add(number);
        mp3.playMP3(song.getSong(number));
        System.out.println("Now Playing " + song.getSong(number));
        System.out.println("Enter \"Stop\" to stop playing the song");
        System.out.println("Enter \"n\" to play the next song");
        line = s.nextLine();
        mp3.stopMP3();
    }while(line.equals("n"));
    mp3.stopMP3();
}
}

我已经做了很多研究,为什么我的程序停止播放我的歌曲,但我找不到任何东西。我做了,发现BlueJ程序没有打开终端窗口(当你执行“System.out.print()”时出现的东西)如果你在输出之前要求输入但我不认为这个计划考虑到了这一点。我还确保当我想播放下一首歌时我输入了一个字符串“n”,对于前几首歌曲,它确实有效,但是在第八首歌之后,它就停止了。我很困惑。

4 个答案:

答案 0 :(得分:7)

我认为唯一的问题在于你用来改组名单的逻辑。

number = r.nextInt(song.size());
boolean done = false;
int counter = 0;
while(!done){
    for(int i = 0; i < songNums.size(); i++){
        if(number == songNums.get(i).intValue()) {number = r.nextInt(song.size()); counter++;}
    }
    if(counter == 0) done = true;
    else done = false;
}

当生成的随机数已存在于songNums列表中时,您将生成一个新的随机数。不会使用所有数量的songNums列表检查此新随机数。以下更改应解决您的问题。

    boolean done = false;
    while(!done){
        number = r.nextInt(song.size());
        if(!songNum.contains(number)) done = true;
    }

或者,您可以在评论中使用Sasha的建议来改组列表(Collections.shuffle())。

答案 1 :(得分:3)

现有算法的实际问题是,当您发现已播放的歌曲时,您不会重置counter。所以一旦你重复一次,就会陷入无限循环 - done永远不会成真。

(实际上,它不会是无限的 - 一旦counter到达Integer.MAX_VALUE,它将回绕到Integer.MIN_VALUE并最终再次到达0,所以如果你离开它足够长,它最终会播放另一首歌)

这里已经提供了一些有关代码改进的有用建议,我在此不再赘述,但是修改所需内容的最小更改是将counter的初始化移至{{1}在循环中:

0

答案 2 :(得分:3)

Sasha在评论中说:使用Collections.shuffle()。在实践中,这将是一个小小的&#39;像这样的东西:

在Music类中有一个获取所有歌曲的方法:

public List<String> getSongs() {return music;}

MusicDriver中的循环将遵循:

List<String> songs = song.getSongs();
do{
    Collections.shuffle(songs);
    for (String songToPly: songs) {
        mp3.playMP3(song.getSong(number));
        System.out.println("Now Playing " + song.getSong(number));
        System.out.println("Enter \"Stop\" to stop playing the song");
        System.out.println("Enter \"n\" to play the next song");
        mp3.stopMP3();
        line = s.nextLine();
        if (!line.equals("n")) break;
    }
}while(line.equals("n"));

在变量命名注释上,将您的音乐类的实例命名为&#34; song&#34; (单数)有点令人困惑。也许叫它&#34;音乐&#34;或者至少&#34;歌曲&#34;。

答案 3 :(得分:0)

我要做的是:

public class MainClass() {

    public static void main(String[] args) {
        PlayerWrapper player = new PlayerWrapper();
    }
}

public class PlayerWrapper() {
    private List<MP3> playlist;
    private Scanner userInputReader;
    private String currentUserInput;

    public PlayerWrapper() {
        userInputReader = new Scanner(System.in());
        System.out.println("Filepath to playlist?");
        String playlistFileName = userInputReader.nextLine();
        playlist = PlayListExtractor.extractPlaylist(playlistFileName);
        start();
    }

    public void start() {
        playlistCopy = new ArrayList<MP3>(playlist);
        shufflePlayList(playlistCopy);
        Iterator<MP3> songIterator = playlistCopy.iterator();
        while (songIterator.hasNext()) {
            MP3 song = songIterator.next();
            songIterator.remove();
            player = new Player(song.toStream());
            player.play();
            displayCurrentSongAndCommands(song);
            currentUserInput = userInputReader.nextLine();
            if ("Stop".equals(currentUserInput )) {
                player.close();
                break;
            } else if ("n".equals(currentUserInput )) {
                player.close();
                continue;
            }
        }

        if("Stop".equals(currentUserInput)) {
            System.out.println("Playlist stopped. Press q to quit or c to continue");
            currentUserInput = userInputReader.nextLine();
            if ("q".equals(currentUserInput)) {
                System.exit(0);
            } else if ("c".equals(currentUserInput)) {
                start();
            }
        }
        start();
    }

    private void shufflePlayList(final List<MP3> playlistToBeShuffled) {
        long seed = System.nanoTime();
        Collections.shuffle(playlistToBeShuffled, new Random(seed));               
    }

    private void displayCurrentSongAndCommands(final MP3 currentSong) {
        System.out.println("Now Playing " + currentSong.toString());
        System.out.println("Enter \"Stop\" to stop playing the song");
        System.out.println("Enter \"n\" to play the next song");
    }
}

public static class PlayListExtractor() {
    private PlayListExtractor();

    public static List<MP3> extractPlayList(final String playListFileName) {
        List<MP3> result = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                result.add(new MP3(line));
            }
            return result;
        } catch (IOException e) {
            System.out.println("Problem parsing playlist");
        }
    }
}

public class MP3 {
    private String filename;

    public MP3(final String filename) {
        this.filename = filename;
    }

    public BufferedInputStream toStream() {
        try {
            FileInputStream fis = new FileInputStream(filename);
            return new BufferedInputStream(fis);                  
        }
        catch (Exception e) {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        } 
    }

    public String toString() {
        return filename;
    }
}