2013-06-25 78 views
0

我有readLine()問題,即我的系統不接受我的任何輸入請求並直接執行下一行我的代碼中有什麼問題我的代碼是:readLine()無法正常工作

System.out.println("Choose your option:\n" 
       + "To Add :\tA/a\n" 
       + "To Delete:\tD/d\n" 
       + "To Update:\tu/U\n" 
       + "To Exit :\tpress any key"); 
     char ch = (char) br.read(); 
     //br.readLine().charAt(0); 
     br.skip(1); 
     if(ch =='a' || ch == 'A'){ 
      addElement(); 
     } 
     else if(ch == 'd' || ch == 'D') { 
      System.out.println("Please enter emp id :"); 
      int id = Integer.parseInt(br.readLine()); 
      //int id = Integer.parseInt(System.console().readLine("enter emp")); 
      deleteElement(id); 
     } 
     else if(ch == 'u' || ch == 'U') { 
      System.out.println("Please enter emp id :"); 
      int id = Integer.parseInt(br.readLine()); 
      updateElement(id); 
     } 
     else System.exit(0); 

這個代碼僅在NetBeans的命令模式下工作是無法訪問的感謝

回答

2

的問題是,第一個字符在這裏閱讀:

char ch = (char) br.read(); 

...將無法使用,直到你」已經擊中回報,此時你有空行。

如果你運行你的代碼,並鍵入

dSomeone 

(然後按回車),那麼你會得到「有人」試圖刪除的名稱。

最簡單的方法可能是使用:

String option = br.readLine(); 
if (option == null) { 
    // User has basically terminated stdin. Die somehow 
} 

if (option.equalsIgnoreCase("D")) { 
    String name = br.readLine(); 
    ... 
} 

另外請注意,這個代碼是沒有用的:

String empName = br.readLine(); 
deleteElement(); 

要求一個名字,但後來忽視它。 deleteElement是如何知道你想刪除哪個員工的?你或許應該做的名字到方法的參數,並提供其打電話時:

String empName = br.readLine(); 
deleteElement(empName); 
0

試試這個,如果你是通過CMD線獲得輸入(終端)

字符串EMP = System.console() .readLine(「請輸入emp名稱」);

+0

這不起作用 –