簡體   English   中英

為什么do-while循環在這個Java程序中沒有按預期運行?

[英]Why does the do-while loop not run as expected in this Java program?

我一直在編寫一個程序,它將采用一系列音樂文件的名稱並播放它們。 我成功地做到了這一點,但是,我想要修改一些東西,讓它更好一些。 我試圖讓音樂以隨機順序播放,但在整個列表播放之前不重復播放任何歌曲。 我幾乎能夠做到,但我認為我的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”,對於前幾首歌曲,它確實有效,但是在第八首歌之后,它就停止了。 我很困惑。

我認為唯一的問題在於你用來改組列表的邏輯。

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())。

現有算法的實際問題是,當您發現已播放的歌曲時,您不會重置counter 因此,只要你重復一次,就會陷入無限循環 - done將永遠不會成真。

(實際上,它不會是無限的 - 一旦counter達到Integer.MAX_VALUE ,它將回繞到Integer.MIN_VALUE並最終再次達到0 ,所以如果你把它留下足夠長的時間它最終會播放另一首歌)

這里有一些關於代碼改進的有用建議,我不會在這里重復它們,但是修改你所擁有的最小變化是在循環內將counter的初始化移動到0

boolean done = false;

while(!done){
    int counter = 0; // reset counter every time

    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;
}

Sasha在評論中說:使用Collections.shuffle()。 在實踐中看起來像這樣的東西:

在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"));

在變量命名注釋上,將Music類的實例命名為“song”(單數)有點令人困惑。 也許稱之為“音樂”或至少稱為“歌曲”。

我會做的是:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM