2014-02-15 26 views
-1
public static void main (String[] args) { 

try{ 
    BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println ("1..case1 | 2..case2"); 
    String ch=Integer.parseInt(bf.readLine());  //user input for switch 
    System.out.println (ch); 
    bf.close(); 
    switch(ch) {     //userinput ch variable switch in case 
     case 1 : 
      String data=bf.readLine(); 
      bf.close(); 
      System.out.println(data); 
      break; 
     case 2 :    
      System.out.print ("Enter Key "); 
      String key=bf.readLine(); 
      bf.close(); 
      System.out.println(key); 
      break; 
     default : 
      System.out.println ("wrong choice");   
    } 
    } 

    catch(IOException e){ 
    System.out.println ("io error"); 
    } 
    bf.close(); 

} 

//每次在第一次用戶輸入後,它進入部分匹配的情況下,但在下一個用戶輸入引發異常。在java中的BufferedReader,總是拋出異常

請幫助.. 在此先感謝..

+1

請告訴我例外呢? –

+5

你想讀一個行郵堆棧跟蹤_after_讀者被關閉。不能這樣做。 –

+0

所以當我應該使用.close()函數.. – sanjitguin

回答

1

它是一種好習慣,收在finally塊其他用途與資源嘗試,如果你正在使用java7或更高版本

看到這個mkyongs example

也行這是錯的String ch=Integer.parseInt(bf.readLine());使它int

您正在轉換bf.readLIne()爲int並存儲在字符串中,這是錯誤的。

另一個錯誤是您在try-catch塊後,關閉bf.close();所以編譯器可能會抱怨

完整的工作代碼

public static void main (String[] args) { 
    BufferedReader bf=null; 

    try{ 
     bf=new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println ("1..case1 | 2..case2"); 
     int ch=Integer.parseInt(bf.readLine());  //user input for switch 
     System.out.println (ch); 

     switch(ch){     //userinput ch variable switch in case 
      case 1 : 
       String data=bf.readLine(); 

       System.out.println(data); 
       break; 
      case 2 :    
       System.out.print ("Enter Key "); 
       String key=bf.readLine(); 

       System.out.println(key); 
       break; 
      default : 
       System.out.println ("wrong choice");   
     } 
    } catch(IOException e){ 
     System.out.println ("io error"); 
     e.printStackTrace(); 
    } 
    finally 
    { 
     try { 
      bf.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 


    } 
+0

請提供更好格式的答案,這很難理解。 –

+0

@AlexisLeclerc我使用移動這樣的感覺很難格式,雖然我已經試過,但它仍然是相同的 – SpringLearner

+0

@AlexisLeclerc請參見現在,我已經格式化 – SpringLearner