java里序列化与反序列化多个输入的商品对象,为啥只输出第一个商品对象的信息(相应的包已导入) 10
publicclassTest6{publicstaticvoidmain(String[]args)throwsException{Scannerinput=newSc...
public class Test6 {
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
String s="",name="";
double total=0.0;
File f=new File("D:/save.ini");
if (!f.exists()) {
f.createNewFile();
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
ArrayList<Goods> list=new ArrayList<Goods>();
do {Goods g1=new Goods();
System.out.print("请输入产品编号:");
g1.setId(input.nextInt());
System.out.print("请输入您要购买的东西的名称:");
g1.setName(input.next());
System.out.print("请输入购买的数量:");
g1.setNum(input.nextInt());
System.out.print("单价:");
g1.setPrice(input.nextDouble());
list.add(g1);
oos.writeObject(list);
oos.flush();
System.out.print("是否继续(y/n):");
s=input.next();
if (s.equalsIgnoreCase("y")) {
continue;
}else if (s.equalsIgnoreCase("n")) {
break;}
} while (true);
oos.close();
fos.close();}
else { FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
System.out.println("\t编号"+"\t产品名"+"\t单价"+"\t数量");
ArrayList<Goods> list1= (ArrayList<Goods>)ois.readObject();
for (Goods goods : list1) {
System.out.println("\t"+goods.getId()+"\t"+goods.getName()+"\t"+goods.getPrice()+"\t"+goods.getNum());
total+=goods.getPrice()*goods.getNum();
}
System.out.println("订单总价为:"+total);
ois.close();
fis.close();
}
}
} 展开
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
String s="",name="";
double total=0.0;
File f=new File("D:/save.ini");
if (!f.exists()) {
f.createNewFile();
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
ArrayList<Goods> list=new ArrayList<Goods>();
do {Goods g1=new Goods();
System.out.print("请输入产品编号:");
g1.setId(input.nextInt());
System.out.print("请输入您要购买的东西的名称:");
g1.setName(input.next());
System.out.print("请输入购买的数量:");
g1.setNum(input.nextInt());
System.out.print("单价:");
g1.setPrice(input.nextDouble());
list.add(g1);
oos.writeObject(list);
oos.flush();
System.out.print("是否继续(y/n):");
s=input.next();
if (s.equalsIgnoreCase("y")) {
continue;
}else if (s.equalsIgnoreCase("n")) {
break;}
} while (true);
oos.close();
fos.close();}
else { FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
System.out.println("\t编号"+"\t产品名"+"\t单价"+"\t数量");
ArrayList<Goods> list1= (ArrayList<Goods>)ois.readObject();
for (Goods goods : list1) {
System.out.println("\t"+goods.getId()+"\t"+goods.getName()+"\t"+goods.getPrice()+"\t"+goods.getNum());
total+=goods.getPrice()*goods.getNum();
}
System.out.println("订单总价为:"+total);
ois.close();
fis.close();
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询