gpt4 book ai didi

java - For 循环中断而不是重复

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:21:14 25 4
gpt4 key购买 nike

我正在编写代码来创建 Java 模板库。我正在编写一段特定的代码,读者将在其中阅读模板的文本并提取占位符 ("${placeholder})。到目前为止,在进行 Jtesting 时,它似乎只使用一个占位符,但是当我尝试不止一个,代码似乎没有循环并读取模板的其余部分。

我这辈子都看不出代码失败的原因。

我已经调试了代码,我能看到的是当它存储第一个占位符时,它没有循环返回,而是丢弃了。

代码如下:

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;

}

}

还有 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);

最佳答案

您当前的解决方案在找到第一个占位符后返回,您可以将其更改为在返回之前遍历 reader 中的所有字符。这是一个例子:

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();
}

关于java - For 循环中断而不是重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com