Wednesday, 24 May 2017

java - ArrayIndexOutOfBoundsException when checking an array?

Answer


Answer




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 list = new ArrayList(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.


Answer



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(" ");

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...