我是Java的新手,我遇到一个错误令我震惊...错误是:
Exception in thread "main" java.lang.NullPointerException
at BancA.carica(BancA.java:30)
at BancA.main(BancA.java:46)
我需要从txt文件中加载一些值...这是由一个ID(Cliente1等),第一个数字(付款)列表和第二个(付款)列表组成的...我决定区分这两个类别将它们分隔为“-” ...但是readLine()似乎读错了一行,或者忽略了我的“ while”语句...无论如何,这是我的代码,您的帮助我们将非常感激:-)
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
最佳答案
第二个readline()
可能遇到EOF,并且在这种情况下tmp2
可能是null
,这导致NullPointerException
。
将while(!(tmp2.equals("-")))
更改为while (tmp2 != null && !tmp2.equals("-"))
可解决您的问题。