Java作业求助:实现StringVerification接口及特殊字符检索
Hey there! Let's tackle your programming assignment issues one by one. First, we'll fix the broken EmailVerification class, then build the PhoneVerification class exactly as you need it—no extra imports required.
Your current EmailVerification has a few key issues:
- Syntax error in
char at = @ ;(you need quotes around the@character) - It returns
trueas soon as it finds an@, without checking for the. - The
dotandatSymbolflags aren't reset between calls toverifyInput(so if you call the method multiple times, old values will stick around) - The constructor's
String atandString periodvariables are unused
Here's the corrected version, with explanations in comments:
public class EmailVerification implements StringVerification { // No need to keep these as instance variables—we can reset them per method call @Override public boolean verifyInput(String input) { // Handle null input first to avoid crashes if (input == null) { return false; } boolean hasAt = false; boolean hasDot = false; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '@') { hasAt = true; } else if (c == '.') { hasDot = true; } // Optional: Early exit if both are found to save processing if (hasAt && hasDot) { break; } } // Return true only if both symbols exist return hasAt && hasDot; } }
A few notes here:
- We declare
hasAtandhasDotinside the method so they reset every timeverifyInputis called - We added a null check to prevent
NullPointerExceptionif someone passesnull - We can optionally break out of the loop early once both symbols are found (not required, but makes the code a bit more efficient)
You mentioned wanting to avoid imports—great news: Character.isDigit() is part of the core java.lang package, which is automatically imported into every Java class, so you don't need any extra import statements. Here's how to implement the class to check for 10-digit pure numbers:
public class PhoneVerification implements StringVerification { @Override public boolean verifyInput(String input) { // First check: input can't be null, and must be exactly 10 characters long if (input == null || input.length() != 10) { return false; } // Check each character to ensure it's a digit for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); // Character.isDigit() checks if the character is a 0-9 digit if (!Character.isDigit(c)) { return false; } } // If we made it here, all checks passed return true; } }
This code:
- Immediately rejects null input or input that isn't 10 characters long
- Iterates through each character, returning false as soon as a non-digit is found
- Returns true only if all characters are digits and the length is correct
That should cover all the requirements of your assignment!
内容的提问来源于stack exchange,提问作者Jose Huertas

