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?
Two possible issues:
When comparing Strings, use .equals(), not ==.
The first element of an array is always 0, not 1.
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;
}
}
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.
I get an error thats confusingis not helpful way to describe your error.CD, notcd). Arrays are zero-indexed. Compare strings (and other objects) with.equals, not==.