1

I've been making a instant chat program, and wanted to make it possible for users to "whisper" or private message one another. The way I implemented that is the user would type:

/w [username] [message]

I then send it to the server which sends it to all the users. The users then have to check to see if its sent to them, this is that method:

if (message.startsWith("/msg/")) {
    message = message.trim();
    message = message.substring(5);
    String[] words = message.split("//s");
    String UserName = null;
    try {
    String username = words[2];
    UserName = username;
    System.out.println(UserName);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Error reading the whisper command!");
    }
    if (UserName == client.getName()) {
        List<String> list = new ArrayList<String>(Arrays.asList(words));
        list.removeAll(Arrays.asList(2));
        words = list.toArray(words);
        String text = words.toString();
        text = "You've been whispered! " + message;
        console(text);
    }

Everytime I send a /w when I'm testing it always give the ArrayIndexOutOfBoundsException. I also modify the message in the sending. Heres that method:

else if (message.toLowerCase().startsWith("/w")) {
    message = "/msg/" + client.getName() + message;
    message = "/m/" + message + "/e/";
    txtMessage.setText("");
}

I also added a whole bunch more options for the actual code for the users, I made it /whisper, /m, /msg, and /message, but those are all just copies of this with a different input. Why is it giving me an ArrayIndextOutOfBoundsException, when the 3rd place in the words array SHOULD be the username that the sender is trying to send it to. Obviously this probably isn't the best way to send private messages, and if any of you guys have a simpler way I can implement to my server, please go ahead and let me know! Just know that I am a young, new programmer and so I will probably have a lot of questions.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
jmaster2013
  • 33
  • 1
  • 7
  • what is your testing message? – Haifeng Zhang Mar 17 '16 at 22:57
  • You do not access an array index and catch ArrayIndexOutOfBounds. You check the length of the array, or arraylist before you access it. Other languages have different concepts here; but in Java you **first check** to ensure that the thing you want to access actually exists before you access it. Splitting strings can always end up with unexpected results; so check first! – GhostCat Mar 17 '16 at 23:01
  • 2
    Did you mean `\\s` rather than `//s`? – bcsb1001 Mar 17 '16 at 23:01

1 Answers1

0

The slashes in your split() regex are backwards. You need

String[] words = message.split("\\s");

You can also just use a space

String[] words = message.split(" ");
spectacularbob
  • 3,080
  • 2
  • 20
  • 41