Skip to content

Instantly share code, notes, and snippets.

@cjmcgraw
Created August 12, 2014 03:19
Show Gist options
  • Save cjmcgraw/ab486eb44ccdde50c275 to your computer and use it in GitHub Desktop.
Save cjmcgraw/ab486eb44ccdde50c275 to your computer and use it in GitHub Desktop.
The initial implementation of a "builder" to build a tree from a formatted text file
import java.io.*;
import java.util.*;
import com.mycompany.guesstheanimal.exceptions.InvalidTreeParsingException;
public class QuestionNodeTreeBuilder implements TreeBuilder<QuestionNode>{
public static final String NODE_DATA_SPLITTER = QuestionNodeTreeWriter.NODE_DATA_SPLITTER;
public static final String QUESTION_PREFIX = QuestionNodeTreeWriter.QUESTION_PREFIX;
public static final String ANSWER_PREFIX = QuestionNodeTreeWriter.ANSWER_PREFIX;
private Iterator<String> input;
private QuestionNode root;
private int lineCounter;
public QuestionNodeTreeBuilder(Iterator<String> input) {
this.lineCounter = 0;
this.input = input;
this.root = null;
}
public QuestionNodeTreeBuilder(File file) throws FileNotFoundException {
this(new Scanner(file));
}
public QuestionNode build() throws InvalidTreeParsingException {
if (invalidRoot())
buildRootAndTree();
return root;
}
private boolean invalidRoot() {
return root == null;
}
private void buildRootAndTree() throws InvalidTreeParsingException {
root = buildSubTree();
}
private QuestionNode buildSubTree() throws InvalidTreeParsingException {
if(input.hasNext()) {
String[] s = readNextFromInput();
String prefix = s[0];
String data = s[1];
if(isQuestion(prefix))
return new QuestionNode(data, buildSubTree(), buildSubTree());
return new QuestionNode(data);
}
invalidStateReached();
return null;
}
private String[] readNextFromInput() {
lineCounter++;
return parseData(input.next());
}
private void invalidStateReached() throws InvalidTreeParsingException {
String msg = "Missing answer node at line # " + lineCounter;
throw new InvalidTreeParsingException(msg, lineCounter);
}
private String[] parseData(String s) {
return s.trim().split(NODE_DATA_SPLITTER, 2);
}
private boolean isQuestion(String prefix) {
return prefix.equals(QUESTION_PREFIX);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment