我正在尝试用 Java 编写一个 madlibs 程序。有一种方法采用模板字符串、该字符串中所有占位符的 ArrayList 以及将替换这些模板的所有用户输入的 ArrayList 作为参数。
该方法如下所示:
private String replacePlaceHolder(String template, ArrayList<String> placeholders, ArrayList<String> replacements){
for (int i = 0; i < placeholders.size(); i++){
template = template.replace(placeholders.get(i), replacements.get(i));
}
return template;
}
问题是,该方法是用替换替换所有出现的给定模板,例如“[形容词]”,而不仅仅是第一个。我尝试template = template.replaceFirst(placeholders.get(i), replacements.get(i))
改用,但它用所有用户输入替换了第一个占位符,并忽略了其余部分。
这是我使用的模板:
Computer programming, also known as [-ing Verb], is a
process that leads from a [Adjective] problem
to an executable [Noun].
Programming often involves [-ing Verb],
[-ing Verb], and [-ing Verb], and can be learned
by anyone!
Source code is written in a programming language,
such as [Animal]code, or Java.
The first ever programmer was [Name of Celebrity],
who invented [Plural Noun] in the year [Year].
Since then, programming has become a
[Adjective] practice all across the world.
我知道占位符的 ArrayList 与模板中的占位符匹配,并且该 ArrayList 与用户输入的 ArrayList 长度相同。
我应该做些什么不同的事情?