Java字符与字符串验证课程代码:代码错误输出问题求助
Hey Larry, let's get your course code validation working correctly. I spotted two key issues in your current code that are causing those unexpected error messages and incorrect validation results:
Key Issues in Your Original Code
Misplaced Error Messages
Your error print statements are placed after thereturn falsecalls for each check. That means when a validation fails, the method exits before printing the error. Worse, when a check passes, it still prints the error message (since the code moves past theifblock and executes the print line). That's why you're seeing all error messages even when some checks pass.Incorrect Final Return Value
At the end of thevalidateCodemethod, you're returningfalseeven if all checks pass. This guarantees that every input will be marked invalid, no matter how correct it is.
Corrected Code
Here's the fixed version with explanations for each change:
package u4a1_validatecoursecode; import java.util.Scanner; public class U4A1_ValidateCourseCode { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter a course code to validate (e.g. IT4782) : "); String code = s.nextLine(); if (validateCode(code)) { System.out.printf("Course code: %s is valid.%n", code); } else { // Error reason is already printed in validateCode, just confirm invalidity System.out.println("Course code is not valid."); } s.close(); // Clean up scanner resource } private static boolean validateCode(String code) { // Check 1: Length must be exactly 6 characters if (code.length() != 6) { System.out.println("Error: Course code must be exactly 6 characters long."); return false; } // Check 2: First character is I or i char firstChar = code.charAt(0); if (firstChar != 'I' && firstChar != 'i') { System.out.println("Error: First character must be 'I' (uppercase) or 'i' (lowercase)."); return false; } // Check 3: Second character is T or t char secondChar = code.charAt(1); if (secondChar != 'T' && secondChar != 't') { System.out.println("Error: Second character must be 'T' (uppercase) or 't' (lowercase)."); return false; } // Check 4: Characters 3-6 are digits (0-9) for (int i = 2; i < 6; i++) { char currentChar = code.charAt(i); if (!Character.isDigit(currentChar)) { System.out.printf("Error: Character at position %d must be a digit (0-9).%n", i + 1); return false; } } // All checks passed! return true; } }
What Changed?
- Error Message Placement: Each error message is now inside the corresponding
ifblock, so it only prints when that specific validation fails. The method returnsfalseright after printing, so it stops checking further conditions (you can adjust this if you want to collect all errors instead of stopping at the first one). - Fixed Return Value: The method returns
trueonly when all validations pass, so correct codes will be marked as valid. - Cleaner Output: Used
printffor more readable messages, and added scanner cleanup to follow best practices. - Loop for Digit Check: Replaced repetitive digit checks with a loop to make the code shorter and easier to maintain.
Test Cases to Verify
- Valid input:
IT4782orit1234→ Outputs "Course code: [code] is valid." - Invalid length:
IT123→ Prints length error. - Wrong first character:
XT4782→ Prints first character error. - Wrong second character:
IY4782→ Prints second character error. - Non-digit in position 6:
IT478a→ Prints position 6 error.
内容的提问来源于stack exchange,提问作者larrys

