import java.io.*; import java.util.*; class Record implements Serializable { private int id; private String name; public Record(int id, String name) { setID(id); setName(name); } public void setID(int id) { this.id= id; } public void setName(String name) { if (name == null) this.name = ""; else this.name = name; } public int getID() { return id; } public String getName() { return name; } public String toString() { return id + ": " + name; } } class Seq3Exception extends Exception { public Seq3Exception() {} public Seq3Exception(String msg) { super(msg); } } class Seq3 { private ObjectOutputStream out = null; public Seq3(String filename) throws Seq3Exception { try { out = new ObjectOutputStream(new FileOutputStream(filename)); } catch (SecurityException e1) { throw new Seq3Exception("Write access to file denied"); } catch (FileNotFoundException e2) { throw new Seq3Exception("File not found"); } catch (IOException e3) { throw new Seq3Exception("I/O Exception"); } } public void close() { if (out != null) { try { out.close(); } catch (IOException e) {} } } public void addRecord(Record r) { try { out.writeObject(r); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } public class TestSeq3 { public static void main(String[] args) { try { Seq3 outfile = new Seq3("records3.txt"); Scanner in = new Scanner(System.in); inloop: while (true) { try { int id = -1; while (id <= 0) { System.out.print("Enter record ID# (^z to exit on Windows, ^d on Mac/UNIX): "); if (!in.hasNext()) break inloop; try { id = Integer.parseInt(in.nextLine()); if (id <= 0) System.out.println("ID# must be greater than 0"); } catch (NumberFormatException e3) { System.out.println("ID must be a positive integer"); id = -1; continue; } } System.out.print("Enter name: "); String name = in.nextLine(); outfile.addRecord(new Record(id, name)); } catch (NoSuchElementException e2) { System.err.println("Invalid input. Try again."); in.nextLine(); } } outfile.close(); } catch (Seq3Exception e1) { System.err.println("Error: " + e1.getMessage()); } } }