Programming Problems: Unique Words +--------------------------------------+ You
ID: 3679332 • 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
There are two method to use a unique comma separator->
1)
import java.util.HashSet;
public class SplitString {
public static void main(String[] args) {
StringBuffer stb = new StringBuffer();
HashSet<String> hashset = new HashSet<String>();
for (String a : st.split("-"))
hashset.add(a);
Object[] str = (Object[]) hashset.toArray();
for (int i = 0; i < str.length; i++) {
stb.append(str[i]);
if (i < str.length - 1)
stb.append("-");
}
System.out.println(stb);
}
2)
import java.util.*;
public class RemoveDuplicateWord {
public static void main(String[] args) {
";
removeDupWord(str);
}
public static void removeDupWord(String input) {
List<String> list = Arrays.asList(input.split(" "));
LinkedHashSet<String> lhs = new LinkedHashSet<String>(list);
for(String s : lhs) {
System.out.print(s+" ");
}
}
}
Key points are:
· split("-") gives us the different values as an array
· Arrays.asList() turns the array into a List
· LinkedHashSet preserves uniqueness and insertion order - it does all the work of giving us the unique values, which are passed via the constructor
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.