Can anyone help fix this code. Need to remove any duplicate words , the last wor
ID: 3547754 • Letter: C
Question
Can anyone help fix this code. Need to remove any duplicate words , the last words in a line , any words less than 8 in length, and any trailing white space, thanks. Example:
dictionary.txt:
a det
ability n
able adj
about adv
about prep
above adv
above rep
absence n
absolutely adv
academic adj
accept v
access n
accident n
accompany v
AAAAA.txt:
absolutely
academic
accident
accompany
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.lang.*;
import java.io.*;
public class RemoveFirstWord
{
public static void main(String args[]) throws Exception
{
String newLine = System.getProperty("line.separator");
String originalFileName = "dictionary.txt";
String newFileName = "AAAA.txt";
PrintWriter outputStream = new PrintWriter(new File ("AAAA.txt"));
Scanner inputStream = new Scanner(new File("dictionary.txt"));
while(inputStream.hasNextLine())
{
String line = inputStream.nextLine();
String[] arr = line.split("\s+");
for(int i = 0; i < arr.length-1; i++)
{
if(arr.length < 8){
outputStream.write(arr[i] + " ");
}
else{continue;}
}
outputStream.write(newLine);
outputStream.flush();
}//end while loop
}//end main
}//end class
Explanation / Answer
DO RATE if u are satisfied
Modifications
Used String.trim() to remove trailing space
Used Set Object for removing duplicates. In a Set on unique objects exist. If u try to add that is already existing that won't be added again
Last words are removed
import java.util.Scanner;
import java.io.PrintWriter;
import java.lang.*;
import java.io.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class dictionary {
public static void main(String args[]) throws Exception {
String newLine = System.getProperty("line.separator");
String originalFileName = "dictionary.txt";
String newFileName = "AAAA.txt";
PrintWriter outputStream = new PrintWriter(new File("AAAA.txt"));
Scanner inputStream = new Scanner(new File("dictionary.txt"));
Set <String> dict = new HashSet<String>();
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
line = line.trim();
String[] arr = line.split("\s+");
if (arr[0].length() >= 8) {
dict.add(arr[0]);
} else {
continue;
}
}
//Iterate all the elements
Iterator it = dict.iterator();
while( it.hasNext() ){
outputStream.write( it.next().toString() +" ");
outputStream.flush();
}//end while loop
}//end main
}//end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.