teaching machines

CS 145 Lecture 12 – File I/O

March 9, 2012 by . Filed under cs145, lectures, spring 2012.

Agenda

TODO

Reverse Engineering

Code

Bored.java

package preexam2;

public class Bored {
  public static void main(String[] args) {

    for (int r = 1; r <= 8; ++r) {
      for (int c = 1; c <= 8; ++c) {
        System.out.printf("%5d", r * c);
      }
      System.out.println();
    }

//    for (int i = 1; i <= 8; ++i) {
//      System.out.printf("%5d", 1 * i);
//    }
//    System.out.println();
//
//    for (int i = 1; i <= 8; ++i) {
//      System.out.printf("%5d", 2 * i);
//    }
//    System.out.println();
//
//    for (int i = 1; i <= 8; ++i) {
//      System.out.printf("%5d", 3 * i);
//    }
//    System.out.println();
//
//    for (int i = 1; i <= 8; ++i) {
//      System.out.printf("%5d", 4 * i);
//    }
//    System.out.println();
  }
}

Dictionary.java

package preexam2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Dictionary {
  public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(System.in);
    System.out.print("Word: ");
    while (in.hasNext()) {
      String entry = lookup(in.next());
      System.out.println(entry);
      System.out.print("Word: ");
    }
  }

  private static String lookup(String term) throws FileNotFoundException {
    File file = new File("/home/user/dictionary.txt");
    Scanner wordGetter = new Scanner(file);

    boolean isMatch = false;
    String line = null;

    while (wordGetter.hasNextLine() && !isMatch) {
      line = wordGetter.nextLine();
      isMatch = line.startsWith(term + ":");
      // if (isMatch) {
      // wordGetter.close();
      // return line;
      // }
    }

    wordGetter.close();

    if (isMatch) {
      return line;
    } else {
      return null;
    }
  }
}

Haiku

Fire. The wheel. Files.
The ancestor inventions.
And patent-free. Whew!