Random Guy Random Guy - 1 month ago 5
Java Question

Java split if it find text after command

I am trying from hours how to do this so I will ask here for help.
I run a IRC bot and trying to do something, when user is sending command to the bot it needs to see if it can spit the input from the user if there is one.

Example: !help lag 2 3;
The code works for this just fine but if the user only send

Example: !help;
Its crashing with

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

Here is the code for that part:

String command = str.split("!")[1];
command = command.split("\\s+", 2)[0];
String username_fix = java.net.URLEncoder.encode(username, "UTF-8").replace("_", "%20");
String combined = "";
String fix = str.split(command)[1];
fix = fix.trim();
String arrayString[] = fix.split("\\s+");
for (int j = 0; j < arrayString.length; j++) {
combined += arrayString[j] + "|";

Error is coming from
String fix = str.split(command)[1];

This did the job done
if (str.split(command).length > 1)
by msrd0.

But and rorschach's answer is the same so i will mark this as solved. Thanks a lot!


Don't try to automatically get the second element of the str.split(command) array. Do the split first and then check if there is a second element there.

String fix = str.split(command)[1];

String[] something = str.split(command);

if(something.length > 1) {
    //rest of your logic