快递e栈
项目执行中调用单号是否存在方法findNum,查询单号时,无论什么情况都返回空值;
//findNum方法
public Expressage findNum(String num) {
Expressage e = new Expressage();
e.setExpressNo(num);
for(int i=0; i<20; i++) {
for(int j=0; j<5; j++) {
if(e.equals(data[i][j])) {
return data[i][j];
}
}
}
return null;
}//错误显示
快递不存在
Exception in thread "main"java.lang.NullPointerException
at com.view.CourierView.out(CourierView.java:25)
at com.view.Estard.courier(Estard.java:115)
at com.view.Estard.menu(Estard.java:35)
at com.view.Estard.main(Estard.java:14)
解决方法:
因为给方法传的值为单号,所以用equal方法比较时应重写equal,且值只为单号变量;
原方法:
其中不止有单号ExpressageNo变量,还有company和code;,但是我们findNum方法中只有expressageNo的值。
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Expressage other = (Expressage) obj;
if (code != other.code)
return false;
if (company == null) {
if (other.company != null)
return false;
} else if (!company.equals(other.company))
return false;
if (expressNo == null) {
if (other.expressNo != null)
return false;
} else if (!expressNo.equals(other.expressNo))
return false;
return true;
}更改后方法:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Expressage other = (Expressage) obj;
if (expressNo == null) {
if (other.expressNo != null)
return false;
} else if (!expressNo.equals(other.expressNo))
return false;
return true;
}问题解决。
快递e栈之加入IO流保存快递信息错误记录
将快递信息写入文件过程:
之前选择
FileOutputStream fos = new FileOutputStream ("d://a.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
但是发现没办法将内容读取到对象;
将方法改为序列化和反序列化
改动过程发现ObjectOutputStream ois = null;定义对象不能方法内部方法外调用,否则会一直报出异常,但是写入成功了;但是放在内部方法里,就会一直new一个ObjectOutputStream对象,覆盖上一次写入;
我使用了方法追加: oos = new ObjectOutputStream(new FileOutputStream(filepath, true));
继续报出异常:抛出 java.io.StreamCorruptedException: invalid type code: AC
网上查找方法重写 ObjectOutputStream---->MyObjectOutputStream
方法如下:
public class MyObjectOutputStream extends ObjectOutputStream {
protected MyObjectOutputStream() throws IOException, SecurityException {
super();
}
@Override
protected void writeStreamHeader() throws IOException {
}
public MyObjectOutputStream(OutputStream o) throws IOException{
super(o);
}
}
异常解决;程序完美运行;
最后发现一个无法更改的大bug:
每次改动一次写入文件就会报出serialVersionUID不匹配的异常:
解决方法:将文本文件删除,重写创建一个;但是下一次改动文件还是会抛出异常;