2013-05-29 28 views
1

我新的Java和我遇到的是真實吹我的腦海裏一個錯誤......錯誤是:錯誤的readLine()的Java讀錯行

Exception in thread "main" java.lang.NullPointerException 
    at BancA.carica(BancA.java:30) 
    at BancA.main(BancA.java:46) 

我需要裝載從一些值txt文件......這是由ID(Cliente1等),數(支付)的第一列表,第二個(傳輸)組成......我已經決定要區分這兩種類別的劃分它們通過「 - 」 ......但的readLine()似乎讀錯線,或者無視我的「而」語句......反正這是我的代碼,你的幫助,我們會如此讚賞:-)

import java.io.*; 
import java.util.*; 
import java.lang.*; 

public class BancA{ 
    private static final String CLIENTI = ("Clienti.txt"); 
    private static ArrayList <Conto> conto = new ArrayList <Conto>(); 
    public static void carica(){ 
     BufferedReader bc; 
     Conto co = new Conto(); 
     String tmp, tmp1, tmp2; 
     try{ 
      bc = new BufferedReader(new FileReader(CLIENTI)); 
      tmp = bc.readLine(); 
      while(tmp!=null){ 
      co.setId(tmp); 
      tmp1 = bc.readLine(); 
      while(!(tmp1.equals("-"))){ 
       co.setBonifico(Integer.parseInt(tmp1)); 
       tmp1 = bc.readLine(); 
      } 
      tmp2 = bc.readLine(); 
      while(!(tmp2.equals("-"))){ 
       co.setVersamento(Integer.parseInt(tmp2)); 
       tmp2 = bc.readLine(); 
      } 
       conto.add(co); 
       co = new Conto(); 
       tmp = bc.readLine(); 
      } 
      System.out.println(conto); 
     } 
     catch(IOException e){ 
      e.printStackTrace(); 
     } 
    } 
public static void main(String [] args){ 
    carica(); 
} 
} 

,這是其他類:

import java.util.*; 
public class Conto{ 
public String id; 
public LinkedList <Integer> bonifico = new LinkedList <Integer>(); 
public LinkedList <Integer> versamento = new LinkedList <Integer>(); 
public Conto(){ 
} 
public void setId(String i){ 
    id = i; 
} 
public void setBonifico(int b){ 
    bonifico.add(b); 
} 
public void setVersamento(int v){ 
    versamento.add(v); 
} 
public String getId(){ 
    return id; 
} 
public LinkedList <Integer> getBonifico(){ 
    return bonifico; 
} 
public LinkedList <Integer> getVersamento(){ 
    return versamento; 
} 
public String toString(){ 
    String str = ("\nId: " +id+ "\nBonifico: " +bonifico+ "\nVersamento:+versamento); 
    return str; 
} 
} 

,而這是我的Clienti.txt文件:

Cliente1 
1 
2 
3 
- 
41 
52 
33 
90 
- 
Cliente2 
4 
- 
89 
3 
1 
+0

哪裏是線30? –

回答

1

第二readline()可以遇到EOF,並tmp2可以null在這種情況下,這會導致NullPointerException

更改while(!(tmp2.equals("-")))while (tmp2 != null && !tmp2.equals("-"))解決您的問題。

0

聲音,好像是沒有找到該文件。您的文件是否與.jar/.class文件位於同一目錄中?

你應該通過一個文件對象添加到您的FileReader,而不是一個字符串。所以你可以檢查一下,如果您通過調用

myFile.exists(); 

選擇了正確的道路( - >應該返回true)

0

EOF reached - NULL

你需要把支票在那裏的EOF。現在,你拋出一個NullPointerException,因爲你在文件的末尾,你期望在那裏看到' - '。 while循環不知道該怎麼做,也無法正常退出。

while循環應該有一個OR條件或者說 「 - 」 或EOF。即使是一個「if」子句來檢查是否已達到EOF。如果是這樣,那麼繼續。

編輯:我剛纔看到宋思雨註釋,他是正確的。 while (tmp2 != null && !tmp2.equals("-"))將工作。我現在就試過了,它像一個魅力。