所以这是我的代码,我知道此问题或类似问题已经发布过。我遇到的冲突是我不应该使用“正则表达式”。我知道这是编写这个程序的一种更简单的方式,但在我的课堂上我们已经没有了。我不是在寻找简单的答案,只是提示。
public class SSNValidatorApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ssn = Validator.getSSN(sc, "Enter a Social Security Number: ");
System.out.println("You entered: " + ssn);
}
}
所以这是第一个显示输出的类,
public static boolean isDigit(char c) {
return Character.isDigit(c);
}
public static boolean isDash(char c) {
return (c == '-');
}
public static String getSSN(Scanner sc, String prompt) {
System.out.println(prompt);
String ssn = sc.next();
String tryAgain = "y";
while (tryAgain.equalsIgnoreCase("y")) {
if (ssn.length() != 11) {
System.out.println(ssn + " is not a valid SSN");
sc.nextLine();
}
for (int i = 0; i < ssn.length(); i++) {
if (i <= 2) {
if (!isDigit(ssn.charAt(i))) {
System.out.println(ssn + " is not a valid SSN");
sc.nextLine();
}
else if (i == 3) {
if (!isDash(ssn.charAt(i))) {
System.out.println(ssn + " is not a valid SSN");
sc.nextLine();
}
}
else if (i == 6) {
if (!isDash(ssn.charAt(i))) {
System.out.println(ssn + " is not a valid SSN");
sc.nextLine();
}
}
else if (i > 6) {
if (!isDigit(ssn.charAt(i))) {
System.out.println(ssn + " is not a valid SSN");
sc.nextLine();
}
}
}
}
tryAgain = Validator.getString(sc, "Would you like to re-enter your SSN? (y/n): ");
System.out.println();
}
return ssn;
}
我的代码中的问题是从最后来的,它应该询问用户“你想重新进入你的SSN吗?他们回答你或者唯一的问题是,当他们回答时,它继续说“”DDD-DD-DDDD“不是有效的SSN”。这是否是我所拥有的if / else if / for / while语句的问题?
感谢。
答案 0 :(得分:2)
您应该在循环开始时向用户查询ssn,即将String ssn = sc.next();
放在while块的顶部。
目前您正在查询用户一次,在while块之后重复使用ssn
的值,而不是在验证之前请求新的。
答案 1 :(得分:0)
for循环是非常不必要的,并且使它更加冗长。如果你真的不能使用正则表达式,只需对每个字符的条件进行硬编码:
if (ssn.length() != 11
|| !isDigit(ssn.charAt(0))
|| !isDigit(ssn.charAt(1))
|| !isDigit(ssn.charAt(2))
|| !isDash(ssn.charAt(3))
|| !isDigit(ssn.charAt(4))
|| !isDigit(ssn.charAt(5))
|| !isDash(ssn.charAt(6))
|| !isDigit(ssn.charAt(7))
|| !isDigit(ssn.charAt(8))
|| !isDigit(ssn.charAt(9))
|| !isDigit(ssn.charAt(10))) {
System.out.println( ssn + " is not a valid SSN");
sc.nextLine();
}