String[] syntax = command.split(" ");
if(syntax[1] == "cd"){
cd cd = new cd();
cd.getCD();
每当我运行它时,我都会收到一个令人困惑的错误。我几乎100%肯定这与字符串或转义有关。我做错了什么?
答案 0 :(得分:4)
两个可能的问题:
比较字符串时,请使用.equals(),而不是==。
数组的第一个元素始终为0,而不是1。
答案 1 :(得分:0)
您尚未关闭if-statement
。对字符串也使用.equals()
而不是==
。
你能展示其余的代码吗?我用你的代码做了一个小工作程序。
在Java ==
中是对象的引用,但是equals()
检查它是否是相同的字符串(逐个字符是相同的)。
自您选择ArrayIndexOutOfBoundsException
而非index 1
后,可能发生了0
。由于索引从Java中的0
开始,这可能是您的问题。
工作示例。
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;
}
}