You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Character类验证用户输入的SSN格式合法性?

SSN Validation with Java's Character Class

Hey Brandon, no worries—let's break this down step by step. Validating an SSN boils down to checking two possible valid formats and ensuring all non-dash characters are digits. Here's how to do it using Character.isDigit() and charAt() like you mentioned:

Step 1: Define the Static Boolean Method

First, create a static method (let's call it isValidSSN) that takes a String input and returns a boolean. We'll handle both valid formats here.

Step 2: Check Basic Length Requirements

A valid SSN is either 10 characters (all digits) or 11 characters (with dashes at positions 3 and 6). If the input length isn't either of these, we can immediately return false.

Step 3: Validate Each Character

  • For the 10-digit format: Loop through every character and confirm it's a digit using Character.isDigit().
  • For the 11-digit format: Check that the 4th character (index 3) and 7th character (index 6) are dashes, then verify all other characters are digits.

Full Code Example

Here's the complete SSNValidator class with comments to explain each part:

import java.util.Scanner;

public class SSNValidator {

    // Static method to validate SSN
    public static boolean isValidSSN(String ssn) {
        // First, check if input is null or empty
        if (ssn == null || ssn.isEmpty()) {
            return false;
        }

        // Check for the two valid lengths
        int length = ssn.length();
        if (length == 10) {
            // Case 1: 10 digits (XXXXXXXXXX)
            for (int i = 0; i < length; i++) {
                char c = ssn.charAt(i);
                if (!Character.isDigit(c)) {
                    return false; // Found a non-digit character
                }
            }
            return true; // All characters are digits
        } else if (length == 11) {
            // Case 2: XXX-XX-XXXX format
            // Check positions 3 and 6 are dashes
            if (ssn.charAt(3) != '-' || ssn.charAt(6) != '-') {
                return false;
            }
            // Check all other positions are digits
            for (int i = 0; i < length; i++) {
                if (i == 3 || i == 6) {
                    continue; // Skip the dash positions we already checked
                }
                char c = ssn.charAt(i);
                if (!Character.isDigit(c)) {
                    return false;
                }
            }
            return true;
        } else {
            // Length is neither 10 nor 11, invalid
            return false;
        }
    }

    // Main method to test the validator with user input
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an SSN to validate: ");
        String userInput = scanner.nextLine();

        if (isValidSSN(userInput)) {
            System.out.println("Valid SSN!");
        } else {
            System.out.println("Invalid SSN format. Use XXXXXXXXXX or XXX-XX-XXXX.");
        }

        scanner.close();
    }
}

Key Notes for You:

  • charAt(index): Remember that Java uses 0-based indexing, so the first character is at index 0, the 4th at index 3, etc.
  • Character.isDigit(c): This method checks if a given character is a numeric digit (0-9). It returns true if it is, false otherwise.
  • Edge Cases: We added checks for null or empty input to avoid runtime errors like StringIndexOutOfBoundsException.

Testing the Code

Try running the program and inputting values like:

  • 1234567890 → Valid
  • 123-45-6789 → Valid
  • 1234-56-789 → Invalid (wrong length)
  • 12a-45-6789 → Invalid (non-digit character)

This should cover all the requirements you mentioned. Let me know if you need clarification on any part!

内容的提问来源于stack exchange,提问作者brandon russk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:17:21