【问题标题】:Add if statements to tokenize添加 if 语句以标记化
【发布时间】:2012-06-02 17:15:54
【问题描述】:

我正在尝试编写一个程序,该程序将使用诸如插入、删除和排序等命令的文本文件,并让它们从链接列表中插入或删除节点。到目前为止,我已经能够标记字符串并将它们写出来;但我也想使用 if 语句,无论文本行是说插入还是说删除。这是我到目前为止所拥有的。感谢您的帮助。

(lane.txt)

         insert 1

         insert 7

         insert 5

         delete 7

         insert 2

         insert 4

         delete 5

还有代码:

导入 java.io.; 导入 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

动作:插入 关键值:5

操作:删除 关键值:7

动作:插入 关键值:2

动作:插入 关键值:4

操作:删除 关键值:5

【问题讨论】:

标签: java if-statement tokenize stringtokenizer


【解决方案1】:

字符串应该使用equals进行比较:

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

【讨论】:

  • @mprabhat action 根据 OP 用于从文件中读取行的代码,永远不会为空。
  • 谢谢大家!我使用 .equals 比较了字符串并解决了它。
【解决方案2】:

现在有了 java 7,我相信你可以在 switch case 中使用字符串。

我猜 java 7 现在允许以下语法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多