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:12 | ISBN:9780132830317 | Edition: 5

Question

(This is a variant of an exercise from Chapter 1.) Create a text file that contains the text "I hate programming!" Write a program that reads in this line of text from the file and then the text with the first occurrence of "hate" changed to "love". In this case, the program would output "I love programming!" Your program should work with any line of text that contains the word "hate", not just the example given in this problem. If the word "hate" occurs more than once in the line, your program should replace only the first occurrence of "hate".


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// HateToLoveFile.java
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class HateToLoveFile
{	
	public static void main(String[] args)
	{
		Scanner fileIn = null;
		try
		{
			fileIn = new Scanner(new FileInputStream("hateText.txt"));
		}
		catch (FileNotFoundException e)
		{
			System.out.println("File not found.");
			System.exit(0);
		}

		System.out.println("Text left to read? " 
						+ fileIn.hasNextLine());
		String stringToBeReplaced = fileIn.nextLine();
		
		System.out.println("The line of text to be changed:");
		System.out.println(stringToBeReplaced);
		
		String replacedString = 
				stringToBeReplaced.replaceFirst("hate", "love");
		
		System.out.println("I have rephrased that line to read:");
		System.out.println(replacedString);

		fileIn.close();
	}
}

Input file: hateText.txt

I hate programming!

Output:

Text left to read? true
The line of text to be changed:
I hate programming!
I have rephrased that line to read:
I love programming!

 

0 0

Discussions

Post the discussion to improve the above solution.