在做一個學校項目時,我一直在遇到以下問題:在從run()
方法(使用控制檯作爲一種文本編輯器)向processCommand()
方法中輸入一行後,我發現對於無論什麼原因,令牌沒有正確讀取,所以我運行到processCommand()
方法的'else'子句,即使命令應該簡單準確(即在控制檯中鍵入h會輸出「請輸入有效的命令」。) 。我敢肯定,我是如何分裂陣容的,但在我的生活中我無法弄清楚。誰能幫我?在Java讀取令牌
@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;
}
}
完美!那就是訣竅。非常感謝! – Akodobo
酷!請標記爲答案=) – awolfe91