2013-12-09 45 views
1

試圖編寫將從文件中讀取數字作爲字符串並將其轉換爲int的代碼。由於某種原因,嘗試從字符串轉換爲int時,代碼崩潰。java.lang.numberformatexception int「」

代碼在Android活動的onCreate函數中執行。 代碼運行正常時,爲sample.txt是空的,但崩潰,並返回以下錯誤,當任何數字都是在sample.txt的文件的第一行:

「java.lang.numberformatexception無效INT‘’」

public static int LastScore; 
public File sdcard = Environment.getExternalStorageDirectory(); 
public File file = new File(sdcard,"sample.txt"); 


    try{ 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
      String line = null; 
      line = br.readLine(); 
     if(line!=null){ 
       LastScore = Integer.parseInt(line); 
         } 

    }catch (IOException e){ 
     System.err.println(e); 
    } 

sample.txt當前在其第一行包含數字「2」。

任何幫助,將不勝感激。

編輯:代碼現在工作。增加了對原始代碼的調整。 感謝您的幫助。

回答

4

您撥打readLine()兩次;一次處於`if``狀態,一次處於下一行。

因此,line第二行行。

+1

謝謝,我懂了! – ConorB

1

什麼@SLaks的意思是,你應該把臺詞:

line = br.readLine(); 
LastScore = Integer.parseInt(line); 
反順序

,改變它的,如果像:

line = br.readLine(); 
if(line != null){ 
    LastScore = Integer.parseInt(line); 
    line = br.readLine(); 
} 

乾杯。

+0

這仍然意味着有2個調用readLine()。你的代碼不是他所說的。 – dymmeh

+0

我更新了,謝謝@dymmeh – prmottajr

+0

乾杯,我現在工作。 – ConorB

相關問題