The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Write a program that starts with a line of text and then outputs that line of text with the first occurrence of "hate" changed to "love" . For example, a possible sample output might be:
The line of text to be changed is:
I hate you.
I have rephrased that line to read:
I love you.
You can assume that the word "hate" occurs in the input. If the word "hate" occurs more than once in the line, your program will replace only the first occurrence of "hate" . Use a defined constant for the string to be changed. To make your program work for another string, you should only need to change the definition of this defined constant.
This is the code that I have written:
public class Question5 {
private static final String STRING_TO_BE_CHANGED = "hate";
public static void main(String[] args) {
System.out.println("The line to be changed is:");
System.out.println(originalLine());
System.out.println("I have rephrased that line to read:");
System.out.println(newLine());
}
private static String originalLine() {
return "I hate you";
}
private static String newLine() {
return originalLine().replaceFirst(STRING_TO_BE_CHANGED, "love");
}
}