Search code examples
javabukkit

Why isn't "<= 1" working as expected?


I have the following code

@EventHandler
public void onPlayerQuit(PlayerQuitEvent event){
    Player player = event.getPlayer();
    final Player[] playerlist = getServer().getOnlinePlayers();
    if (playerlist.length <=1) { // if no players are online
        getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
            // this is a scheduler.
            public void run(){
                 if(playerlist.length <=1){
                     getServer().shutdown();
                 }
            }
        }, 6000L); // runs every 6000 ticks, which is every 300 seconds, which is every 5 minutes.
 }
}

Which when a player leaves, it checks to see if he was the last one on, if he was, then it after 5 minutes, it checks again, and if still no one is on its supposed to stop the server.

In this line here:

if (playerlist.length <=1) { // if no players are online

I HAVE to have it as <=1 or it doesnt work at all, but it will also stop the server if I leave, and join back and im the only one on. When I had it at =0 and just <1 it didnt work.

Any ideas?

Here is my update code (Still doesnt work):

 @EventHandler
public void onPlayerQuit(PlayerQuitEvent event){
    Player player = event.getPlayer();
    final Player[] playerlist = getServer().getOnlinePlayers();
    if (playerlist.length <=1) { // if no players are online
        getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
            // this is a scheduler.
            public void run(){
                final Player[] playerlist = getServer().getOnlinePlayers(); 
                if(playerlist.length <=1){
                     getServer().shutdown();
                 }
            }
        }, 500L); // runs every 6000 ticks, which is every 300 seconds, which is every 5 minutes.
 }
}

Solution

  • The reason why what you have written does not work is your use of <=. If someone logs off and no one is left, the task is scheduled. If someone logs back on within 5 minuets or less and remains online, when the scheduled task checks to see if the server should be shutdown, 1 <= 1 is true so the server shuts down.

    You mentioned that just using = did not work, this is because in boolean statements, == must be used to check for equality.

    Try using this:

    if (playerlist.length == 0) { // if no players are online
        // Do stuff
    }
    

    Update (Discussed in comments): I do not know the Bukkit API very well, but this is what I assume is happening then: The online player list is updated after onPlayerQuit() is executed. Try this: Inside of your onPlayerQuit() method, try checking playerlist.length == 1 and inside of your task, check playerlist.length == 0