2012-12-04 93 views
3

在做一個學校項目時,我一直在遇到以下問題:在從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; 
    } 
} 

回答

3

您不應該使用「==」進行字符串比較。使用以下內容:

if(tokens[0].equals("h"))... 

希望有所幫助!

+0

完美!那就是訣竅。非常感謝! – Akodobo

+0

酷!請標記爲答案=) – awolfe91

0

僅供參考,下面是一個使用switch語句(也許更容易閱讀或更少的字符鍵入)的替代版本:

public void processCommand(String line) { 
    String[] tokens = line.split(" "); 
    if(tokens[0].length() == 0) { 
     System.out.println("Please enter a valid command."); 
     return; 
    } 
    switch(tokens[0].charAt(0)) { 
     case 'b': insertBefore(line.substring(3)); 
        break; 
     case 'i': insertAfter(line.substring(3)); 
        break; 
     case 'm': moveUp(Integer.parseInt(line.substring(3))); 
        break; 
     case 'u': moveDown(Integer.parseInt(line.substring(3))); 
        break; 
     case 'r': 
     case 'd': remove(Integer.parseInt(line.substring(3))); 
        break; 
     case 'c': clear(); 
        break; 
     case 's': try { 
         save(line.substring(3)); 
        } catch (IOException e) { } 
        break; 
     case 'l': try { 
         load(line.substring(3)); 
        } catch (IOException e) { } 
        break; 
     case 'h': displayHelp(); 
        break; 
     case 'x': exit(); 
        break; 
     default: System.out.println("Please enter a valid command."); 
    } 
}