THINK FIRST·CODE LATER

← All labs

Find and replace in a file

Problem

ReplaceInFile corrects a word everywhere in a text file. The input gives the word to replace (line 1), the new word (line 2) and then the text. The program must:

  1. write the text into the file letter.txt with a PrintWriter;
  2. call replaceInFile(File source, File target, String oldWord, String newWord), which reads letter.txt line by line with a Scanner, writes the corrected lines into letter-corrected.txt and returns the number of replacements;
  3. read letter-corrected.txt back and print it with line numbers, followed by a summary;
  4. delete both files in a finally block.

Also write occurrences(String line, String word) with indexOf. For the input

teh
the
Dear students, teh lab starts at nine.
Please bring teh handbook and teh laptop.
See you there.

the program prints

1: Dear students, the lab starts at nine.
2: Please bring the handbook and the laptop.
3: See you there.
Replaced "teh" by "the" 3 time(s) in 3 line(s)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l17-8-data-1.txt

teh
the
Dear students, teh lab starts at nine.
Please bring teh handbook and teh laptop.
See you there.
What your program must print for l17-8-data-1.txt
1: Dear students, the lab starts at nine.
2: Please bring the handbook and the laptop.
3: See you there.
Replaced "teh" by "the" 3 time(s) in 3 line(s)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l17-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l17-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.