Solved /msg string

Discussion in 'Spigot Plugin Development' started by OopsyPoopsy, May 2, 2017.

Thread Status:
Not open for further replies.
  1. Hello Spigot.

    I'm currently coding /msg for my plugin and for the string, it always returns as the players username. I know I could easily replace the targets username with "" but I don't want to block the name completely.

    Code (Java):

    @Override

    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {

    if (cmd.getName().equalsIgnoreCase("msg")) {

    if (args.length == 0) {

    sender.sendMessage("§c/message <player> <message>");

    return true;

    }

    Player target = Bukkit.getPlayer(args[0]);


    if (target == null) {

    sender.sendMessage("§cCould not find player " + args[0]);

    return true;

    }

    String msg = "";

    for (String arg : args) {

    msg += arg + " ";

    msg = msg.substring(0, msg.length() - 1);

    target.sendMessage("§7(From §a" + sender.getName() + " §7" + msg + ")");

    sender.sendMessage("§7(To §a" + target.getName() + " §7" + msg + ")");

    return true;

    }

    }

    return true;

    }
     
     
    #1 OopsyPoopsy, May 2, 2017
    Last edited: May 2, 2017
  2. The foreach loop iterates over all the entries. That would include the target name. You're going to want to do for(int i = 1; i < args.length - 1; i++) { } to collect the actual message
     
  3. Here is a video on a messaging system.
     
  4. Code (Text):
    String msg = "";

    For (int i = 1; i < args.length; i++) {
        msg += args[i] + " ";
    }
    You can use a StringBuilder but this is the idea for simplicity. It starts at 1 because the 0th index is the player name.

    Also, you need to fix your {} around your for loop, unless you copied and pasted it wrong. Otherwise the loop will just run one time, print, and return.
     
  5. Thank you guys! I fixed it!
     
Thread Status:
Not open for further replies.