(This is a better version of an exercise from Chapter 1.) Write a program that reads in 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 dialog might be the following:
Enter a line of text.
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 should replace only the first occurrence of "hate".
Program:
// HateToLove.java
import java.util.Scanner;
public class HateToLove
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text.");
String stringToBeReplaced = keyboard.nextLine();
String replacedString =
stringToBeReplaced.replaceFirst("hate", "love");
System.out.println("I have rephrased that line to read:");
System.out.println(replacedString);
keyboard.close();
}
}
Output:
Enter a line of text.
I love you.
I have rephrased that line to read:
I love you.
import java.util.Scanner;
public class HateToLove {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String hate = "hate";
String love = "love";
System.out.println("Enter a sentence: ");
String sentence = keyboard.nextLine();
if (sentence.indexOf(hate) == -1)
{
System.out.println("There is no hate in the entered line. ");
}
else {
int hateIndex = sentence.indexOf(hate);
System.out.println("changed sentence:");
System.out.println(sentence.substring(0,hateIndex) + love + sentence.substring(hateIndex+4));
}
keyboard.close();
}
}
Post the discussion to improve the above solution.