javaboy
javaboy

Reputation: 57

java.lang.ArrayIndexOutOfBoundsException error when splitting strings

String[] syntax = command.split(" ");

if(syntax[1] == "cd"){

    cd cd = new cd();
    cd.getCD();

Whenever I run this, I get an error thats confusing. I am almost 100% sure this has to do with strings or escaping. What did I do wrong?

Upvotes: 0

Views: 296

Answers (2)

knordbo
knordbo

Reputation: 552

You haven't closed your if-statement. Also use .equals() not == for strings. Can you show of the rest of the code? I made a small working program with your code.

In Java == is the reference of the object, but equals() checks if it's the identical string (character by character is identical).

The ArrayIndexOutOfBoundsException might have occurred since you chose index 1 instead of 0. Since indexes start at 0 in Java this might be your problem.

Working example.

public static void main(String[] args) {
    String command = "cd temp";
    String[] syntax = command.split(" ");

    if(syntax[0].equals("cd")){
        CD cd = new CD();
        cd.getCD();
        System.out.println(cd.getCD());
    }
}
static class CD {
    private String title;

    public CD() {
        title = "unnamed";
    }

    public String getCD() {
        return title;
    }
}

Upvotes: 0

wvdz
wvdz

Reputation: 16641

Two possible issues:

When comparing Strings, use .equals(), not ==.

The first element of an array is always 0, not 1.

Upvotes: 4

Related Questions