0

I am trying to write a program that will take a text file with commands such as insert, delete and sort and have them insert or delete a node from a linked list. So far I have been able to tokenize the strings and write them out; but I also want to use if statements whether the text line says to insert or if it says delete. This is what I have so far. Thank you for any help.

(lane.txt)

         insert 1

         insert 7

         insert 5

         delete 7

         insert 2

         insert 4

         delete 5

And the code:

import java.io.; import java.util.;

class 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

} // end class

The output:

Action: insert Key Value: 1

Action: insert Key Value: 7

Action: insert Key Value: 5

Action: delete Key Value: 7

Action: insert Key Value: 2

Action: insert Key Value: 4

Action: delete Key Value: 5

Lane Fujikado
  • 135
  • 1
  • 3
  • 11
  • possible duplicate of [Java String.equals versus ==](http://stackoverflow.com/questions/767372/java-string-equals-versus) – Jeffrey Jun 02 '12 at 17:18

2 Answers2

3

Strings should be compared using equals:

if (action.equals("insert")) { // etc.
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

Well with java 7 in place now, I believe you can use strings in switch case.

I guess java 7 now allows the following syntax:

String s = ....;
switch(s)
{
   case "insert": 
      break;
   default:
      break;
}
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
dharam
  • 7,882
  • 15
  • 65
  • 93