import java.io.*;
class AccountInfo {
private String lastName;
private String firstName;
private int age;
private float accountBalance;
protected AccountInfo(final String last,final String first,final int ag,final float balance) throws IOException{
lastName=last;
firstName=first;
age=ag;
accountBalance=balance;
}
public void saveState(final OutputStream stream){try{
OutputStreamWriter osw=new OutputStreamWriter(stream);
BufferedWriter bw=new BufferedWriter(osw);
bw.write(lastName);
bw.newLine();
bw.write(firstName);
bw.write(age);
bw.write(Float.toString(accountBalance));
bw.close();}
catch(IOException e){
System.out.println (e);
}
}
public void restoreState(final InputStream stream)throws IOException{
try{
InputStreamReader isr=new InputStreamReader(stream);
BufferedReader br=new BufferedReader(isr);
lastName=br.readLine();
firstName=br.readLine();
age=Integer.parseInt(br.readLine());
accountBalance=Float.parseFloat(br.readLine());
br.close();}
catch(IOException e){
System.out.println (e);
}
}
}
class accounto{
public static void main (String[] args) {try{
AccountInfo obj=new AccountInfo("chaturvedi","aayush",18,18);
FileInputStream fis=new FileInputStream("Account.txt");
FileOutputStream fos=new FileOutputStream("Account,txt");
obj.saveState(fos);
obj.restoreState(fis);}
catch(IOException e){
System.out.println (e);
}
}
}
我收到以下错误:线程“main”中的异常 java.lang.NumberFormatException:null
在 java.lang.Integer.parseInt(Integer.java:454)
在 java.lang.Integer.parseInt(Integer.java:527)
在 AccountInfo.restoreState(accounto.java:43)
在 accounto.main(accounto.java:60)
这是你的代码:
BufferedReader br=new BufferedReader(isr);
//...
age=Integer.parseInt(br.readLine());
这是文档BufferedReader.readLine()(粗体我的):
包含该行内容的字符串,不包括任何行终止字符,or null
如果已到达流末尾
事实上,您从未真正检查是否达到 EOF。你能确定你的输入吗(事实证明你不能)。
还为Integer.parseInt():
Throws:
NumberFormatException
- 如果字符串不包含可解析的整数。
null
几乎不是一个“可解析整数“。最简单的解决方案是检查您的输入并以某种方式处理错误:
String ageStr = br.readLine();
if(ageStr != null) {
age = Integer.parseInt(br.readLine())
} else {
//decide what to do when end of file
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)