在做一个学校项目时,我遇到了以下问题:在processCommand()
从run()
方法中向方法中输入一行之后(使用控制台作为一种文本编辑器),我发现无论出于何种原因,令牌都无法正确读取因此,processCommand()
即使命令应该简单而准确(即在控制台中键入 h 会显示“请输入有效命令。”),我也会运行该方法的“else”子句。我确定我如何拆分线路有问题,但对于我的生活,我无法弄清楚。谁能帮我?
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
String line;
try {
do {
System.out.print("vi: ");
line = scanner.nextLine();
if(line.length() > 0){
processCommand(line);
}
} while (!quit);
} catch (Exception ex) {
System.out.println("An error occurred.");
}
scanner.close();
System.out.println("Goodbye!");
}
@Override
public void processCommand(String line) {
String[] tokens = line.split(" ");
if(tokens[0] == "b") {
insertBefore(line.substring(3));
}
if(tokens[0] == "i") {
insertAfter(line.substring(3));
}
if(tokens[0] == "m") {
moveUp(Integer.parseInt(line.substring(3)));
}
if(tokens[0] == "u") {
moveDown(Integer.parseInt(line.substring(3)));
}
if(tokens[0] == "r") {
remove(Integer.parseInt(line.substring(3)));
}
if(tokens[0] == "d") {
remove(Integer.parseInt(line.substring(3)));
}
if(tokens[0] == "c") {
clear();
}
if(tokens[0] == "s") {
try {
save(line.substring(3));
} catch (IOException e) {
}
}
if(tokens[0] == "l") {
try{
load(line.substring(3));
} catch (IOException e) {
}
}
if(tokens[0] == "h") {
displayHelp();
}
if(tokens[0] == "x") {
exit();
}
else {
System.out.println("Please enter a valid command.");
return;
}
}