Java Applet垃圾邮件检测:关键词匹配代码问题求助
Fixing Your Spam Keyword Matching Issue
Let’s walk through the problems in your code and get that keyword matching working correctly:
Key Issues in Your Current Code
- Wrong Comparison Logic: You’re checking if the entire email input equals the string representation of your spam words array (which looks like
[Various words]), instead of checking if the email contains each individual spam word. That’s why your matches never trigger as expected. - Broken Counter Increment:
SpamCounter = SpamCounter++won’t actually increase your counter. The post-increment operator returns the original value before incrementing, so assigning it back cancels out the change. Just useSpamCounter++directly. - Annoying Dialogs: Showing a pop-up for every spam word (match or no match) will quickly become frustrating. You likely only want to notify when a spam word is found, or just display the final count.
Corrected Code
Here’s the fixed version with these issues addressed, plus some Java best practices like lowercase variable names:
int spamCounter = 0; String[] spamWords = new String[] { "free", "win", "prize", "various words" }; // Replace with your actual spam terms String emailInput = EmailTA.getText().toLowerCase(); // Convert email to lowercase once for consistent matching for (String spamWord : spamWords) { String lowerSpamWord = spamWord.toLowerCase(); if (emailInput.contains(lowerSpamWord)) { JOptionPane.showMessageDialog(this, "Found spam word: " + spamWord); spamCounter++; // Properly increment the counter } } String result = "Your Spam Count is: " + spamCounter; JOptionPane.showMessageDialog(this, result);
Extra Improvements to Consider
- Exact Word Matches: The current code matches partial words (e.g., "win" would catch "winner"). If you want to match whole words only, use regex with word boundaries:
if (emailInput.matches(".*\\b" + Pattern.quote(lowerSpamWord) + "\\b.*")) { spamCounter++; }Pattern.quote()ensures special characters in your spam words don’t break the regex. - Performance: For large spam word lists, swap the array for a
HashSet<String>of lowercase terms—this makes lookups faster than looping through an array every time.
内容的提问来源于stack exchange,提问作者jaxpcdrs
相关产品推荐
相关产品推荐

