1

我是 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
4

3 回答 3

1

第二种readline()可能会遇到 EOF,并且tmp2可能是null在这种情况下,这会导致NullPointerException.

更改while(!(tmp2.equals("-")))while (tmp2 != null && !tmp2.equals("-"))解决您的问题。

于 2013-05-29T14:44:35.133 回答
0

听起来,好像找不到文件。您的文件是否真的与 .jar/.class 文件位于同一目录中?

您应该将 File-object 传递给 FileReader,而不是字符串。所以你可以检查,如果你通过调用选择了正确的路径

myFile.exists();

(-> 应该返回 true)

于 2013-05-29T14:34:21.010 回答
0

达到 EOF - NULL

你需要在那里检查EOF。现在,您正在抛出 NullPointerException,因为您位于文件的末尾,并且您希望在那里看到一个“-”。while 循环不知道该做什么,也无法正常退出。

while 循环应该有一个 OR 条件来表示“-”或 EOF。甚至还有一个“if”子句来检查是否已达到 EOF。如果是这样,那么继续。

编辑:我刚看到宋思雨的评论,他是对的。while (tmp2 != null && !tmp2.equals("-"))将工作。我现在刚试了一下,它就像一个魅力。

于 2013-05-29T15:03:31.210 回答