import java.io.Serializable;
import java.util.Hashtable;
public class SpamFilter implements Serializable {
private Hashtable<String, String> badWords; // hash table that hold a list
// of bad words.
/**
* defalut constructor that create an instance of SpamFilter.
*/
public SpamFilter() {
badWords = new Hashtable<String, String>();
}
/**
*
* @param word
* insert the word into bad words list.
*/
public void insert(String word) {
/**
* if it is already in the list, no need to insert again.
*/
if (isBadWord(word))
System.out.println(word
+ " is already in Hashtable, no need to insert.");
/**
* insert to the list if it is not in the list yet.
*/
else {
badWords.put(word, word);
System.out.println(word + " is added to Hashtable.");
}
}
/**
*
* @param word
* remove the word if it is in list.
* @throws ElementNotFoundException
* when there is no such element found.
*/
public void remove(String word) throws ElementNotFoundException {
/**
* remove the word if it is found.
*/
if (isBadWord(word)) {
badWords.remove(word);
System.out.println(word + " is removed from Hashtable.");
}
/**
* not found then throw an exception.
*/
else
throw new ElementNotFoundException(word
+ " is not found in the Hashtable.");
}
/**
*
* @param checkMe
* check if the given String is in the hashtable or not.
* @return true if it is. false if it is not.
*/
public boolean isBadWord(String checkMe) {
return (badWords.containsKey(checkMe));
}
/**
*
* @param message
* open the file of the given message.
* @return the % that contain spam words.
*/
public float checkEmail(String message) {
String[] messages = message.split(" ");// split the sentences
int countBadWords = 0;
for (String s : messages)
// check each word if it is a spam or not.
if (isBadWord(s))
countBadWords++; // increment by 1 if it is.
return (float) countBadWords / messages.length; // return the %
}
}


雷达卡



京公网安备 11010802022788号







