Question

Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter...

Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter called dataFile (representing the path to a text file) and uses a Set of Strings to eliminate duplicate words from dataFile. The unique words should be stored in an instance variable called uniqueWords. Create an instance method called write that takes a single parameter called outputFile (representing the path to a text file) and writes the words contained in uniqueWords to the file pointed to by outputFile. The output file should be overwritten if it already exists, and created if it does not exist.

Create a separate class called Application that contains a main method which illustrates the use of DuplicateRemoverby calling both the remove and write methods. Your input file must be called problem1.txt and your output file must be called unique_words.txt.

Your program should work on any text file. The TA's will provide their own version of problem1.txt when they run your code.

In java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Application Class

public class Application {

    public static void main(String[] args) {

      DuplicateRemover dr = new DuplicateRemover();

      dr.remove("problem1.txt");

      dr.write("unique_words.txt");

    }

   

}

//DuplicateRemover Class

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Iterator;

import java.util.LinkedHashSet;

public class DuplicateRemover {

    private LinkedHashSet<String> uniqueWords;

    public DuplicateRemover() //constructor that initializes uniqueWords

    {

        uniqueWords = new LinkedHashSet<>();

    }

    public void remove(String dataFile) {

        File f1 = new File(dataFile);

        FileReader fr = null;

        BufferedReader br = null;

        try {

            fr = new FileReader(f1); //Creation of File Reader object

            String[] words = null;

            String s;

            br = new BufferedReader(fr); //Creation of BufferedReader object

            while ((s = br.readLine()) != null) //Reading Content from the file

            {

                s = s.replaceAll("[.,?!)(]", " "); //eliminate fullstops, commas, etc

                words = s.split("\\s+"); //Split the word using space, multiple spaces treated as one using regex

                for (String word : words) {

                    uniqueWords.add(word.toLowerCase()); //add word to set, set doesn't contain duplicate elements

                }

            }

        } catch (IOException ex) {

            System.err.println(ex.getMessage());

        } finally {

            //close everything that's opened

            try {

                if (fr != null) {

                    fr.close();

                }

                if (br != null) {

                    br.close();

                }

            } catch (IOException ex) {

            }

        }

    }

    public void write(String outputFile) {

        BufferedWriter out = null;

        Iterator it = uniqueWords.iterator();

        try {

            out = new BufferedWriter(new FileWriter(outputFile));

            while (it.hasNext()) {

                out.write(it.next().toString());

                out.newLine(); //write next word on a new line

            }

        } catch (IOException ex) {

        } finally {

            try {

                if(out!=null)

                    out.close();

            } catch (IOException ex) {

            }

        }

    }

}

Code screenshots:

Application Class

public class Application { public static void main(String[] args) { DuplicateRemover dr = new DuplicateRemover(); dr.remove (

DuplicateRemover Classimport java.io. BufferedReader; import java.io. BufferedWriter; import java.io.File; import java.io.FileReader; import java.i

for (String word : words) { uniqueWords.add (word. toLowerCase()); //add word to set, set doesnt contain duplicate elementstry { if (out!=null) out.close(); } catch (IOException ex) {

Input file: problem1.txt

problem 1.txt - Notepad Eile Edit Format View Help Create a class called DuplicateRemover. Create an instance method called r

Output file: unique_words.txt

10 unique_words.txt X create 2 a 3 class called 5 duplicateremover an instance 8 method remove that 11 takes 12 single parame

60 62 unique_words.txt 43 output 44 overwritten 45 if 46 it already 48 exists 49 created 50 does 51 not 52 exist 53 separate

Add a comment
Know the answer?
Add Answer to:
Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Programming assignment. 1. Create a class called Square that takes a width parameter in the...

    Java Programming assignment. 1. Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw() method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw() method on the square object. Below is a UML diagram for the Square and Rectangle class: 3. Create a zip file that contains your Java programs....

  • Create a Python class named Phonebook with a single attribute called entries. Begin by including a...

    Create a Python class named Phonebook with a single attribute called entries. Begin by including a constructor that initializes entries to be an empty dictionary. Next add a method called add_entry that takes a string representing a person’s name and an integer representing the person’s phone number and that adds an entry to the Phonebook object’s dictionary in which the key is the name and the value is the number. For example: >>> book = Phonebook() >>> book.add_entry('Turing', 6173538919) Add...

  • Create a class Circle with one instance variable of type double called radius. Then define an...

    Create a class Circle with one instance variable of type double called radius. Then define an appropriate constructor that takes an initial value for the radius, get and set methods for the radius, and methods getArea and getPerimeter. Create a class RightTriangle with three instance variables of type double called base, height, and hypotenuse. Then define an appropriate constructor that takes initial values for the base and height and calculates the hypotenuse, a single set method which takes new values...

  • Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one...

    Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one for the hour, one for the minute and one for the second. Your class should have the following methods: A default constructor that takes no parameters (make sure this constructor assigns values to the instance variables) A constructor that takes 3 parameters, one for each instance variable A mutator method called setHour which takes a single integer parameter. This method sets the value of...

  • [Java] Create a class called FileExercises that contains the following method Method encrypt that does not...

    [Java] Create a class called FileExercises that contains the following method Method encrypt that does not return anything and takes a shift, input filename and output filename as arguments. It should read the input file as a text file and encrypt the content using a Caesar cypher with the shift provided. The resulting text should be placed in the output file specified. (If the output file already exists, replace the existing file with a new file that contains the required...

  • Create a class called Date212 to represent a date. It will store the year, month and...

    Create a class called Date212 to represent a date. It will store the year, month and day as integers (not as a String in the form yyyymmdd (such as 20161001 for October 1, 2016), so you will need three private instance variables. Two constructors should be provided, one that takes three integer parameters, and one that takes a String. The constructor with the String parameter and should validate the parameter. As you are reading the dates you should check that...

  • In this assignment, you will explore more on text analysis and an elementary version of sentiment...

    In this assignment, you will explore more on text analysis and an elementary version of sentiment analysis. Sentiment analysis is the process of using a computer program to identify and categorise opinions in a piece of text in order to determine the writer’s attitude towards a particular topic (e.g., news, product, service etc.). The sentiment can be expressed as positive, negative or neutral. Create a Python file called a5.py that will perform text analysis on some text files. You can...

  • The following code uses a Scanner object to read a text file called dogYears.txt. Notice that...

    The following code uses a Scanner object to read a text file called dogYears.txt. Notice that each line of this file contains a dog's name followed by an age. The program then outputs this data to the console. The output looks like this: Tippy 2 Rex 7 Desdemona 5 1. Your task is to use the Scanner methods that will initialize the variables name1, name2, name3, age1, age2, age3 so that the execution of the three println statements below will...

  • List of Candles Create a class called CandleNode which has fields for the data (a Candle)...

    List of Candles Create a class called CandleNode which has fields for the data (a Candle) and next (CandleNode) instance variables. Include a one-argument constructor which takes a Candle as a parameter. (For hints, see the PowerPoint on "Static vs. Dynamic Structures”.) public CandleNode (Candle c) { . . } The instance variables should have protected access. There will not be any get and set methods for the two instance variables. Create an abstract linked list class called CandleList. This...

  • Create a new class called DemoSortingPerformacne Create a private method called getRandomNumberArray. It returns an array...

    Create a new class called DemoSortingPerformacne Create a private method called getRandomNumberArray. It returns an array of Integer and has 2 parameters: arraySize of type int and numberOfDigits of type int. This method should create an array of the specified size that is filled with random numbers. Each random numbers should have the same number of digits as specified in the second parameter In your main method (or additional private methods) do the following: Execute selection sort on quick sort...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT