[英]How can I use the sp variable in the if at the top?
I am working on a Minecraft Bukkit plugin, using this API.我正在使用此API 开发 Minecraft Bukkit 插件。 The problem I'm having is that I want to use the sp variable in the code below, to check if it is playing using .isplaying() (a method of the API), in the if-statement at the top.我遇到的问题是我想在下面的代码中使用 sp 变量,以检查它是否正在使用 .isplaying() (API 的一种方法)在顶部的 if 语句中播放。 The problem is, is that the sp variable is created inside the if-statement.问题是, sp 变量是在 if 语句中创建的。 So how can I use that sp variable in the if-statement when the method is ran again?那么当该方法再次运行时,如何在 if 语句中使用该 sp 变量呢?
If I'm not clear enough, tell me.如果我不够清楚,请告诉我。 Also I'm pretty new to java, so bear that in mind.此外,我对 Java 还很陌生,所以请记住这一点。
-JustRamon -JustRamon
public void playTune(String eventTune, Player p)
{
if (Methods.getSongPath(eventTune).exists()) //&& sp.isplaying()
{
Song s = NBSDecoder.parse(Methods.getSongPath(eventTune));
SongPlayer sp = new RadioSongPlayer(s);
sp.setAutoDestroy(true);
sp.addPlayer(p);
sp.setPlaying(true);
}
else
{
notFound(eventTune);
}
}
First of all, if you want to access the object with multiple calls to your method, you want a reference to the object.首先,如果你想通过多次调用你的方法来访问对象,你需要一个对对象的引用。 So you should declare a variable inside your class like so:所以你应该在你的类中声明一个变量,如下所示:
private SongPlayer sp;
Then change your method as follows:然后按如下方式更改您的方法:
public void playTune(String eventTune, Player p)
{
/*Creates sp if it is null (When it is null, we know that there is no
RadioSongPlayer object referenced by sp)*/
if (Methods.getSongPath(eventTune).exists()) && sp == null)
{
Song s = NBSDecoder.parse(Methods.getSongPath(eventTune));
sp = new RadioSongPlayer(s);
sp.setAutoDestroy(true);
sp.addPlayer(p);
sp.setPlaying(true);
}
else
{
notFound(eventTune);
}
//Now that sp is not null, we know that it references a SongPlayer object, that is,
//the object we just created in the first if statement
if(sp != null){ /
//sp was created
//Use sp
}
}
I won't recommend you to do this tho.我不会建议你这样做。 It will be better to refactor your first if
to another method because creating a SongPlayer
shouldn't be a concern of your playTune
method.最好将您的第一个if
重构为另一种方法,因为创建SongPlayer
不应该是您的playTune
方法的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.