Formatted input

I was in need for formatted input and the decomposition of the input into a stream of tokens so i came up with the following:

// +—————————————————————————
// | Author: Tim Van Wassenhove <timvw@users.sourceforge.net>
// | Update: 2005-03-19 14:39:00
// |
// | Make formatted input easier, example:
// |
// |      BufferedReader input = new BufferedReader(new FileReader("file.txt"));
// |      for (String in = input.readLine()) {
// |        TokSequence ts = new TokSequence(new StringTokenizer(in));
// |        int userId = ts.getIn();
// |        double score = ts.getDouble();
// |        String name = ts.getString();
// |        // do stuff with userId, score and name
// |      }
// +—————————————————————————
import java.util.*;

public class TokSequence {
  private StringTokenizer tk;

  public TokSequence(StringTokenizer tk) {
    this.tk = tk;
  }

  public int getInt() {
    return Integer.valueOf(tk.nextToken()).intValue();
  }

  public double getDouble() {
    return Double.valueOf(tk.nextToken()).doubleValue();
  }

  public String getString() {
    return tk.nextToken();
  }
}
 

Download the source for TokSequence.java.txt.

And now i am ready for formatted input like this:

public class Main {
  public static void main(String[] args) {
    try {
      BufferedReader input = new BufferedReader(new FileReader("file.txt"));
      for (String in = input.readLine()) {
        TokSequence ts = new TokSequence(new StringTokenizer(in));
        int userId = ts.getIn();
        double score = ts.getDouble();
        String name = ts.getString();
        // do stuff with userId, score and name
      }
    } catch (Exception e) {
      System.err.println(e);
      System.exit(1);
    }
  }
}

This entry was posted on Saturday, March 19th, 2005 at 01:31 and is filed under Java. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.