Expanding your code

Before testing the code, let's improve on the onEnable method by implementing an if statement. If there is only one player online, then why not say hello to that specific player? We can get a collection of all the players that are online by calling Bukkit.getOnlinePlayers. If we wish to check whether the size of the collection is equal to 1, we can accomplish this by using an if/else statement. This is demonstrated in the following code:

if (Bukkit.getOnlinePlayers().size() == 1) {//Only 1 player online
  //Say 'Hello' to the specific player
} else {
  //Say 'Hello' to the Minecraft World
  broadcastToServer("Hello World!");
}

Within the if statement, we will now get the first and the only object in the collection of players. Once we have it, we can continue by broadcasting Hello along with the player's name. After completing the if statement, the entire class will look like the following code:

package com.codisimus.myfirstbukkitplugin;

 importorg.bukkit.Bukkit;
 importorg.bukkit.entity.Player;
 importorg.bukkit.plugin.java.JavaPlugin;

    /**
    * Broadcasts a hello message to the server
    */
public class MyFirstBukkitPlugin extends JavaPlugin {
  @Override
  public void onEnable() {
    if (Bukkit.getOnlinePlayers().size() == 1) {

      //Loop through the collection to access the single player
      for (Player player : Bukkit.getOnlinePlayers()) {
        //Say 'Hello' to the specific player
        broadcastToServer("Hello " + player.getName());
      }
    } else {
        //Say 'Hello' to the Minecraft World
        broadcastToServer("Hello World!");
      }
    }

    /**
    * Sends a message to everyone on the server
    *
    * @param msg the message to send
    */
    private void broadcastToServer(String msg) {
      Bukkit.broadcastMessage(msg);
    }
  }

Tip

If you do not fully understand the if statement or the code provided, then I suggest that you go to my website to learn the basics of Java, which is a prerequisite that was mentioned in the preface of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.131.168