-
Duplicating words
So here is the problem I am faced with:
Write a program called DuplicateWords.java. This program has a countDuplicates method
that accepts a Scanner for an input file and a PrintStream for an output file as its parameters.
Your program should examine each line looking for consecutive occurrences of the same
token on the same line and print each duplicated token, along with the number of times that it
appears consecutively. Non-repeated tokens are not printed. You may ignore the case of
repetition across multiple lines (such as if a line ends with a given token and the next line
starts with the same token). You program should also print out the line number of those
duplicate words. The input filename is either duplicate.txt or a name accepted from the
console, and the output filename is either duplicateReport.txt or a name accepted from the
console. For example, consider the following input:
Hello how how are you you you you
I I I am Jack’s Jack’s smirking smirking smirking smirking revenge
Bow wow wow yippee yippee yo yippee yippee yay yay yay
One fish two fish red fish blue fish
It’s the Muppet show, wakka wakka wakka
Your method should produce the following output and write it into a file:
Line 1: how*2 you*4
Line 2: I*3 Jack’s*2 smirking*4
Line 3: wow*2 yippee*2 yippee*2 yay*3
Line 5: wakka*3
Here is the code I have so far:
Code:
import java.io.*;
import java.util.*;
public class DuplicateWords {
public static void main(String args[]) throws FileNotFoundException {
Scanner input = new Scanner(new File("duplicate.txt"));
PrintStream output = new PrintStream(new File("duplicateReport.txt"));
while (input.hasNext()) {
String line = input.next();
countDuplicates(line);
}
}
static int count = 0;
public static void countDuplicates(String line) {
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String id = lineScan.next();
}
}
}
I'm not exactly how top go on. any tips about how to proceed? Do I have to write an if statement for each separate word? Help please.
-
A couple of things:
"First, I think you set up your method wrong as directed in the instructions. It says to pass in a Scanner as a parameter". This was Josh's opening observation in your word wrap thread. He gave an example there that would be just as relevant and useful here.
Secondly, do you understand how the example output was obtained from the example input? Can you hide that output and figure out what the output should be? How?
I ask these three questions because their answers are key to making any progress with the countDuplicates() method. Once you have a clear (precise/detailed) series of steps that you know you would follow yourself to obtain that output then you can begin to convert them into code so that the computer can do the same thing.
If you get stuck with this then say what it is you are trying to do (the precise and detailed steps) and at which step you are stuck.