I am trying to write a madlibs program in Java. There is a method that takes a template String, an ArrayList of all the placeholders in that String, and an ArrayList of all the user inputs that will replace those templates, as parameters.
The method looks like this:
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;
}
The problem is, the method is replacing all occurrences of a given template, such as "[Adjective]" with the replacement, instead of just the first one. I tried using template = template.replaceFirst(placeholders.get(i), replacements.get(i)) instead, but it replaced the first placeholder with all of the user inputs, and ignored the rest.
Here is the template I used:
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.
I know that the ArrayList of placeholders matches the placeholders in the template, and that that ArrayList is the same length as the ArrayList of user inputs.
What should I be doing differently?
replaceFirstis the correct answer, but the parameters are regex expressions, so you need to quote the search text, especially since it uses[], which is special regex for a character class.To quote the values, use
Pattern.quote(String s)for the first parameter, andMatcher.quoteReplacement(String s)for the second parameter.Here is a Minimal, Reproducible Example, something you should have provided in the question:
Output