Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I, have, been, a, happy, man, ever, since, January, 1, 1990, when, no, longer, h

ID: 3673426 • Letter: I

Question

            I, have, been, a, happy, man, ever, since, January, 1, 1990, when, no,             longer, had, an, email, address, used, about, 1975, and, it, seems,             to, me, that, 15, years, of, is, plenty, for, one, lifetime.            Requirements         +--------------------------------------+          1. Use the input file "text.txt" provided along with assignment.          2. Use the ArrayList class to compile the unique words/terms.                ArrayList<String> words = new ArrayList<String>();          3. The output should be the unique words separated by commas.          4. The source code must be formatted and documented. 

Explanation / Answer

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;

public class UniqueWordsList {
   /**
   * @param args
   * @throws FileNotFoundException
   */
   public static void main(String[] args) {

       try {

           Scanner fileScanner = new Scanner(new File("text.txt"));
           fileScanner.useDelimiter("[^A-Za-z0-9]");
           // declare arraylist
           ArrayList<String> words = new ArrayList<String>();
           // reading data from text file
           while (fileScanner.hasNext()) {
               // getting word by word
               String word = fileScanner.next();
               // if the word not contains in the list then add the list
               if (!words.contains(word)) {
                   words.add(word);
               }
           }

           // sort the list
           Collections.sort(words);
           // printing the size
           System.out.println("There are " + words.size() + " unique word(s)");
           System.out.println("These words are:");
           // printing the words in the list
           for (Iterator<String> it = words.iterator(); it.hasNext();) {
               String f = it.next();
               System.out.println(f);
           }
           fileScanner.close();

       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       }
   }
}

text.txt:

I, have, been, a, happy, man, ever, since, January, 1, 1990, when, no,
longer, had, an, email, address, used, about, 1975, and, it, seems,
to, me, that, 15, years, of, is, plenty, for, one, lifetime.

OUTPUT:

There are 36 unique word(s)
These words are:

1
15
1975
1990
I
January
a
about
address
an
and
been
email
ever
for
had
happy
have
is
it
lifetime
longer
man
me
no
of
one
plenty
seems
since
that
to
used
when
years