繁体   English   中英

我如何正确使用布尔值来使用方法的不同部分

[英]How can i correctly use boolean to use different parts of a method

我有一个MP3Player类,它具有方法pressStop。 我想检查是否在重置播放列表之前使用了该方法,以及是否只是暂停歌曲。 我尝试过在不同的部分使用它们,但无济于事。 我将不胜感激的解释代码:

public void pressStop() {
        boolean isStopped = false;
        if(isStopped) {
            currentSong = 0;
            System.out.println("Songs are stopped");

        }
        if(!isStopped){
            System.out.println("Song " + currentSong + " is stopped");
            isStopped = true;
        }
    }

该代码将无法正常工作。

isStopped始终为false,因此永远不会输入第一个条件


处理这些动作的一种方法是使用回调侦听器,就像任何流行的GUI框架都会提供按钮单击一样。

这里的想法-您拥有一个维护玩家“状态”的类,并且从该类外部注入作用于该状态的任何事件。

public class MP3Player {

    private boolean playing; // defaults to false
    private MP3Player.StopButtonListener stopListener;

    public MP3Listener(StopButtonListener stopListener) {
        this.stopListener = stopListener;
        // TODO: Add listeners for other buttons, like start/next/prev
    }

    public interface StopButtonListener {
        public void onStopClicked();
    }

    public void stop() {
        System.out.println("stopping player!");
        this.playing = false;
        if (this.stopListener != null) {
            this.stopListener.onStopClicked();
        }
    }

    // TODO: add start

}

这样,您可以在mp3播放器停止时添加操作。

public class MP3Demo {

    public static void main(String[] args) {

        MP3Player.StopButtonListener l = new MP3Player.StopButtonListener() {
            @Override
            public void onStopClicked() {
                System.out.println("got stop event for player!");
                // TODO: Reset the player, update some other information in your app, etc.
            }
        };
        final MP3Player p = new MP3Player(l);
        p.stop();
    }

}

您将在方法开始时设置isStopped变量。 这总是false

你可以试试 :

public void pressStop() {
    // boolean isStopped = false; 
    if (isStopped) {
        currentSong = 0;
        System.out.println("Songs are stopped");
    } else {
        System.out.println("Song " + currentSong + " is stopped");
    }
    isStopped = true;
}

public void pressPlay() {
    // set the currentSong and do whatever
    isStopped = false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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