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:
Console Input And Output
Exercise:
Programming Projects
Question:9 | ISBN:9780132830317 | Edition: 5

Question

(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".


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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.

 

0 0

Discussions

sinaaa

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.