In: Computer Science
Java Programming: spellcheck
Write code to read in a dictionary from the current directory called "dict.txt" (you can find this in the current directory/data)
Add each word to a hash map after splitting words and throwing away punctuation (see the demo).
open a file called "spell.txt" to check in the current directory.
Print out every word in spell.txt that is NOT in the
dictionary.
Example:
if spell.txt contains:
hello, this is a test. 2152189u5
Misspelled! cApitalized
The output should be:
2152189u5
Misspelled
cApitalized
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map.Entry;
public class SpellCheck {
private static HashMap<String, String> readWords(String fileName) throws IOException {
var lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
var itr = lines.iterator();
var map = new HashMap<String, String>();
while (itr.hasNext()) {
var words = itr.next().split("\\W");
for (String word : words) {
if (!map.containsKey(word))
map.put(word.toLowerCase(), word);
}
}
return map;
}
public static void main(String[] args) throws IOException {
var dictWords = readWords("dict.txt");
var fileWords = readWords("spell.txt");
for (Entry<String, String> word : fileWords.entrySet()) {
if(!dictWords.containsKey(word.getKey()))
System.out.println(word.getValue());
}
}
}
Contect of dict.txt |
hello, this is a sample test dictionary. |
Content of spell.txt |
hello, this is a test. 2152189u5 Misspelled! cApitalized |
Output |
cApitalized 2152189u5 Misspelled |
Code with sample input output.