Java SSN校验isValid方法误报非数字错误问题排查修复
问题修复方案
错误原因
- 分支逻辑写反:当遍历到第3、第6位(下标从0开始)时,这两个位置本身就应该是短横线,你反而加了逻辑校验这两个位置是数字,合法SSN到这里必然触发非数字报错。
- 校验范围遗漏:你只处理了下标为3和6的位置,其余应该为数字的位置完全没有做校验。
- 返回值错误:校验全部通过后方法返回
false,导致合法SSN也不会触发成功提示。 - 短横线校验冗余:每次到下标3、6时都重复判断两个位置的短横线,不需要重复执行。
修复后的完整代码
SocSecException类(无改动)
public class SocSecException extends Exception { public SocSecException (String error){ super("Invalid the social security number, " + error); } }
SocSecProcessor类(修正isValid方法+修正输入提示拼写错误)
import java.util.Scanner; public class SocSecProcessor{ public static void main(String args[]){ Scanner input = new Scanner(System.in); String name,SSN; String response; char answer ='Y'; while(Character.toUpperCase(answer)== 'Y'){ try{ System.out.print("Name? "); name = input.nextLine(); System.out.print("SSN? "); SSN= input.nextLine(); if (isValid(SSN)){ System.out.println(name + " With "+ SSN + " is Valid"); } } catch (SocSecException e){ System.out.println(e.getMessage()); } System.out.print("Continue? "); // 修正原拼写错误Conitnue response = input.nextLine(); answer = response.charAt(0); } input.close(); } public static boolean isValid (String ssn) throws SocSecException{ // 校验长度 if(ssn.length()!=11){ throw new SocSecException("wrong number of characters"); } // 遍历每一位校验 for(int index = 0; index < 11; index++){ char current = ssn.charAt(index); if(index == 3 || index == 6){ // 第3、6位必须是短横线 if(current != '-'){ throw new SocSecException ("dashes at wrong positions"); } }else{ // 其余位置必须是数字 if(!Character.isDigit(current)){ throw new SocSecException ("contains a character that is not a digit"); } } } // 全部校验通过返回true return true; } }
校验逻辑说明
现在的校验顺序完全符合需求:
- 先校验SSN长度是否为11,不符合直接抛出对应异常
- 遍历每一位字符:
- 下标为3、6的位置校验是否为短横线,不符合抛出短横线位置错误异常
- 其余位置校验是否为数字,不符合抛出非数字异常
- 全部校验通过返回
true,触发合法提示
内容的提问来源于stack exchange,提问作者Nat
相关产品推荐
相关产品推荐

