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?

javaboy
  • 57
  • 1
  • 7
  • Examples on the values of command please? – kzidane Nov 18 '13 at 00:53
  • You should take a look at [how-do-i-compare-strings-in-java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). Also `I get an error thats confusing` is not helpful way to describe your error. – Pshemo Nov 18 '13 at 00: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 `==`. – Kevin Nov 18 '13 at 00:56

2 Answers2

4

Two possible issues:

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

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

wvdz
  • 16,251
  • 4
  • 53
  • 90
  • 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. – kzidane Nov 18 '13 at 01:07
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;
    }
}
knordbo
  • 552
  • 3
  • 7
  • If you are sure that it is not problem then why you are posting this as answer instead of comment? – Pshemo Nov 18 '13 at 00:55
  • @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! – knordbo Nov 18 '13 at 00:57
  • 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. – Pshemo Nov 18 '13 at 01:21