SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Getting Started
Exercise:
Programming Projects
Question:5 | ISBN:9780132830317 | Edition: 5

Question

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". Since we will not discuss input until Chapter 2, 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.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// HateToLove.java
public class HateToLove
{
	public static final String STRING_TO_BE_CHANGED = "I hate you.";
	
	public static void main(String[] args)
	{
		String replacedString = STRING_TO_BE_CHANGED.replaceFirst("hate", "love");
		
		System.out.println("The line of text to be changed is:");
		System.out.println(STRING_TO_BE_CHANGED);		
		
		System.out.println("I have rephrased that line to read:");
		System.out.println(replacedString);
	}
}

Output:

The line of text to be changed is:
I hate you.
I have rephrased that line to read:
I love you.

 

0 0

Discussions

Post the discussion to improve the above solution.