2012-06-02 33 views
0

我正在嘗試編寫一個程序,它將帶有一個文本文件的命令插入,刪除和排序,並讓它們從鏈表中插入或刪除一個節點。到目前爲止,我已經能夠標記字符串並將它們寫出來;但我也想使用if語句來判斷文本行是否插入或者是否刪除。這是我迄今爲止所擁有的。感謝您的任何幫助。添加if語句來標記化

(lane.txt)

  insert 1 

     insert 7 

     insert 5 

     delete 7 

     insert 2 

     insert 4 

     delete 5 

,代碼:

進口java.io. ; import java.util。;

類TokenTest {

public static void main (String[] args) { 
    TokenTest tt = new TokenTest(); 
    tt.dbTest(); 
} 

void dbTest() { 

    DataInputStream dis = null; 
    String dbRecord = null; 

    try { 

     File f = new File("lane.txt"); 
     FileInputStream fis = new FileInputStream(f); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     dis = new DataInputStream(bis); 

     // read the first record of the database 
     while ((dbRecord = dis.readLine()) != null) { 

      StringTokenizer st = new StringTokenizer(dbRecord, " "); 
      String action = st.nextToken(); 
      String key = st.nextToken(); 


      System.out.println("Action: " + action); 
      if(action == "insert") 
      { 
       System.out.println("holla"); 
      } 
      System.out.println("Key Value: " + key); 
      if(action == "delete") 
      { 
       System.out.println("holla"); 
      } 
      System.out.println(" "); 


     } 

    } catch (IOException e) { 
     // catch io errors from FileInputStream or readLine() 
     System.out.println("Uh oh, got an IOException error: " + e.getMessage()); 

    } finally { 
     // if the file opened okay, make sure we close it 
     if (dis != null) { 
      try { 
      dis.close(); 
      } catch (IOException ioe) { 
      System.out.println("IOException error trying to close the file: "); 
      } 

     } // end if 

    } // end finally 

} // end dbTest 

} //結束類

輸出:

操作:插入 密鑰值:1

操作:插入 項值:7

動作:inse室溫 項值:5

操作:刪除 項值:7

操作:插入 項值:2

操作:插入 項值:4

操作:刪除 Key Value:5

+0

可能重複(http://stackoverflow.com/questions/767372/java-string-equals -versus) – Jeffrey

回答

3

字符串應該使用equals

if (action.equals("insert")) { // etc. 
+0

@mprabhat根據OP用於從文件中讀取行的代碼,「action」不會爲空。 –

+0

謝謝大家!我使用.equals比較了字符串並解決了這個問題。 –

0

那麼現在用java 7就可以了,我相信你可以在switch case中使用字符串。

我猜的Java 7現在允許的語法如下:[Java的String.equals與==]的

String s = ....; 
switch(s) 
{ 
    case "insert": 
     break; 
    default: 
     break; 
} 
+0

謝謝,我會明確記住這一點。 –