gpt4 book ai didi

java - Error readLine() Java读取错误行

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:21 24 4
gpt4 key购买 nike

我是 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("-"))) 可以解决您的问题。

关于java - Error readLine() Java读取错误行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com