0
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?

3
  • Examples on the values of command please? Commented Nov 18, 2013 at 0:53
  • You should take a look at how-do-i-compare-strings-in-java. Also I get an error thats confusing is not helpful way to describe your error. Commented Nov 18, 2013 at 0:53
  • Where to start. Classes should start with a capital (CD, not cd). Arrays are zero-indexed. Compare strings (and other objects) with .equals, not ==. Commented Nov 18, 2013 at 0:56

2 Answers 2

4

Two possible issues:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I guess it is always one possible issue that is related to ArrayIndexOutOfBoundsExceptions that is the used index does not exist. comparing strings with either == or equals() is not the main issue as long as the string to be compared doesn't exit.
0

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;
    }
}

3 Comments

If you are sure that it is not problem then why you are posting this as answer instead of comment?
@Pshemo I can't put code in comment. Also the issue might be index etc. so I'm going to make a working example here!
First part of your answer: You haven't closed your if-statement. Also use .equals() not == for strings. Can you show of the rest of the code? is good comment, but it doesn't answer the question why OP is getting ArrayIndexOutOfBoundsException. Also showing working example is not the same as explaining what changes you made and why ware they necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.