import java.io.*; import java.util.*; class Record { 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 Seq1Exception extends Exception { public Seq1Exception() {} public Seq1Exception(String msg) { super(msg); } } class Seq1 { private Formatter out = null; public Seq1(String filename) throws Seq1Exception { try { out = new Formatter(filename); } catch (SecurityException e1) { throw new Seq1Exception("Write access to file denied"); } catch (FileNotFoundException e2) { throw new Seq1Exception("File not found"); } } public void close() { if (out != null) { try { out.close(); } catch (Exception e) {} } } public void addRecord(Record r) { try { out.format("%d:%s\n", r.getID(), r.getName()); } catch (FormatterClosedException e) { System.err.println("Error writing to output file"); } } } public class TestSeq1 { public static void main(String[] args) { try { Seq1 outfile = new Seq1("records.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 (Seq1Exception e1) { System.err.println("Error: " + e1.getMessage()); } } }