How to check if an argument is a player?

Discussion in 'Plugin Development' started by the_merciless, Oct 28, 2012.

Thread Status:
Not open for further replies.
  1. Offline


    Like the title says.

    I am using

    Player p = Bukkit.getPlayer(args[1]);

    But that returns an error if the string is not equal to a player
  2. Offline


    Off the top of my mind there are two ways to do this.
    1. Use a try/catch
    2. Check if the player == null
  3. Offline


    I thought about a try/catch but i want to send a player a message saying they didnt specify a real player.
    Wouldnt checking if the player is null be too late as i would have already set the variable giving the error?

    Maybe if i combined the 2 it would stop me receiving the error and give me a way to send the message
  4. Offline


    2. Player other = Bukkit.getServer().getPlayer(args[0]);
    4. if(other == null)
    5. {
    6. player.sendMessage(ChatColor.RED+"Error: Player "+ChatColor.YELLOW+args[0]+ChatColor.RED+" is not online");
    7. return true;
    8. }

    Ignore bad spacing.. :p
  5. Offline


    But i get "an internal error has occured"

    Surely that is sent as soon as it trys this
    Player other = Bukkit.getServer().getPlayer(args[0]);
  6. Offline


    Surely nothing, it tells you where the NPE is :p show us the line you know it is coming from :p
  7. Offline


    If(Bukkit.getServer().getPlayer(args[0])!=null) continue...
  8. Offline


    hehe i didnt check, i just assumed. The NPE is given after setting the variable. so i can easily just add a null check after it. Thanks guys.
Thread Status:
Not open for further replies.

Share This Page