[英]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.