I'm writing code to create a java template library. I'm writing a specific piece of code where a reader will read the text of the template and pull out placeholders ("${placeholder}). So far, when Jtesting, it seemed to work with a single placeholder, but when I try more than one, the code doesn't seem to loop back and read the rest of the template.
I can't, for the life of me, see why the code is failing.
I've debugged the code, and all I can see is that when it stored the first placeholder, it's not looping back, but instead it's dropping out.
Code is as follows:
import java.io.IOException;
import java.io.Reader;
public class placeholderFinder {
private Reader reader;
public placeholderFinder(Reader reader) {
this.reader = reader;
}
public static final int NORMALTEXT = 0;
public static final int PLACEHOLDERTEXT = 1;
private int state = NORMALTEXT;
private StringBuilder placeholder = new StringBuilder();
public String nextPlaceholderFinder() throws IOException {
for (int p = reader.read(); p != -1; p = reader.read()) {
if (p == '$') {
if (state == NORMALTEXT) {
state = PLACEHOLDERTEXT;
placeholder.append((char) p);
}
} else if (state == PLACEHOLDERTEXT) {
placeholder.append((char) p);
}
if (p == '}') {
if (state == PLACEHOLDERTEXT) {
state = NORMALTEXT;
String placeholderStore = placeholder.toString();
placeholder.setLength(0);
return placeholderStore;
}
}
}
return null;
}
}
And the Jtest
@Test
void testWithPlaceholders() throws IOException {
Reader reader = new StringReader("a ${name} ${date}");
placeholderFinder finder = new placeholderFinder(reader);
String expectedresult = "${name}${date}";
String actualcode = finder.nextPlaceholderFinder();
assertEquals(expectedresult, actualcode);
Your current solution return after the first placeholder is found, you can change it to go through all the characters in the reader
before returning. Here is an example:
public String nextPlaceholderFinder() throws IOException {
for (int p = reader.read(); p != -1; p = reader.read()) {
if (p == '$') {
if (state == NORMALTEXT) {
state = PLACEHOLDERTEXT;
placeholder.append((char) p);
}
} else if (state == PLACEHOLDERTEXT) {
placeholder.append((char) p);
}
if (p == '}') {
if (state == PLACEHOLDERTEXT) {
state = NORMALTEXT;
}
}
}
return placeholder.toString();
}