<span style="white-space:pre"> </span>System.out.print("input numbers of the company :"); Numbers=scanner.nextInt(); Company company; company=new Company(Numbers); company.input(); ObjectOutputStream file=new ObjectOutputStream(new FileOutputStream(new File("Company.txt"))); file.writeObject(company); file.close(); ObjectInputStream out=new ObjectInputStream(new FileInputStream(new File("Company.txt"))); company=(Company)(out.readObject()); <span style="color:#ff0000;"> System.out.print("input name:"); <span style="white-space:pre"> </span>name=scanner.nextLine(); company.output(name,"numbers"); System.out.print("input numbers:"); numbers=scanner.nextLine(); company.output(numbers,"numbers"); </span>
中间加红的代码段看上去并没有什么问题,但是在输入的时候却直接跳过了input name: ,这就让我感到很奇怪了,起初我以为是自己对象序列化方面有些错误所导致的问题,但是检查了半天也没发现问题,后来我想起了以前在C语言读取字符时遇到的一个类似问题,根本原因就是看不到的回车字符被nextline()读取了,最上面的那行代码刚好在录入Numbers时输入了回车符,在我们不知道的情况下读取了,所以导致接下来的name字符无法录入,跳过一行,但下面的numbers却能正常读写
解决这个问题,只需要在input name 上面一行加入如下代码即可:
scanner.nextLine();//吸收上个输入最后的回车字符