Programming Problems: Unique Words +--------------------------------------+ You
ID: 3679708 • Letter: P
Question
Programming Problems: Unique Words +--------------------------------------+ You are to write a Java program that processes an input text file and identifies the unique words or terms in the file. For instance, given the text in the "Input Text" below, the result would be as shown in the "Output Text" section. Input Text: "I have been a happy man ever since January 1, 1990, when I no longer had an email address. I had used email since about 1975, and it seems to me that 15 years of email is plenty for one lifetime." Output Text: 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.util.*;
import java.io.*;
public class Indexer
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner fileScanner = new Scanner(new File("File.txt"));
fileScanner.useDelimiter("[^A-Za-z0-9]");
ArrayList<String> words = new ArrayList<String>();
while (fileScanner.hasNext())
{
String nextWord = fileScanner.next();
if (!words.contains(nextWord))
{
words.add(nextWord);
}
}
Collections.sort(words);
System.out.println("There are " + words.size() + " unique word(s)");
System.out.println("These words are:");
for (Iterator<String> it = words.iterator(); it.hasNext();)
{
String f = it.next();
System.out.print(f+", ");
}
fileScanner.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.