2011-03-11 43 views
0

在我的程序中,我想從文本文件中讀取。我的文件中的數據是由空格分隔的數字。我會在我的程序中將它們轉換爲整數。如果從文件讀取的數據不是數字,我想捕獲異常。我想知道文件的哪一行發生了錯誤(數據不是數字)。我知道我應該趕上NumberFormatException異常,但不知道如何找到異常行。 這裏是一個代碼位:如何知道IOexception發生在文件的哪一行

try 
{ 
    //...using Bufferreader ...some code here 
    while ((strLine = br.readLine()) != null) 
    { 
    String[] term = strLine.split(" "); 
    //for now i just work with the first element of the array 
    int num = Integer.parseInt(term[0]); 
    //....some code here 
    } 
    in.close(); 
} 
catch (NumberFormatException eg) 
{ 
    System.out.println("Error: there is a problem in line ..? "); 
} 

回答

0
int num = Integer.parseInt(term[0]); 

上面一行將拋出NumberFormatException的參數時不會號碼。

4
int line = 0; 
try 
{ 
    //...using Bufferreader ...some code here 
    while ((strLine = br.readLine()) != null) 
    { 
    line ++; 
    String[] term = strLine.split(" "); 
    //for now i just work with the first element of the array 
    int num = Integer.parseInt(term[0]); 
    //....some code here 
    } 
    in.close(); 
} 
catch (NumberFormatException eg) 
{ 
    System.out.println("Error: there is a problem in line " + line); 
} 
相關問題