UseCourse.java
Select all
/* UseCourse.java CIS 260 David Klick 2012-01-23 This program demonstrates how data can be written to a file sequentially. It also demonstrates the use of the Formatter class to write to a file. */ import java.util.*; import java.io.FileNotFoundException; public class UseCourse { private static Formatter out; public static void main(String[] args) { openFile("courses.txt"); addCourses(); if (out != null) out.close(); } private static void openFile(String filename) { try { out = new Formatter(filename); } catch (SecurityException se) { System.err.println("Write access denied."); System.exit(1); } catch (FileNotFoundException fe) { System.err.println("Error creating file."); System.exit(2); } } private static void addCourses() { String dept, sec, room, name; int num; Scanner in = new Scanner(System.in); while (true) { System.out.print("Enter department (QUIT to exit): "); dept = in.next(); if (dept.equalsIgnoreCase("QUIT")) break; System.out.print("Enter course number: "); num = in.nextInt(); System.out.print("Enter section: "); sec = in.next(); System.out.print("Enter room number: "); in.nextLine(); // skip previous newline room = in.nextLine(); System.out.print("Enter course name: "); name = in.nextLine(); Course c = new Course(dept, num, sec, room, name); try { out.format("%s|%d|%s|%s|%s\n", c.getDepartment(), c.getCourseNumber(), c.getSection(), c.getRoom(), c.getName()); } catch (FormatterClosedException e1) { System.err.println("Error writing to file."); System.exit(3); } catch (NoSuchElementException e2) { System.err.println("Invalid input - record not written."); in.nextLine(); } } } }