Reputation: 13
So here is my code, I understand that this question or a similar has been posted before. The conflict I've come across is that I'm not supposed to be using "regex". I know that's a more simplistic way of writing this program but it's nothing we've gone over yet in my class. I'm NOT looking for easy answers, just tips.
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);
}
}
So this is the first class to display output,
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;
}
The issue in my code is coming from the end, where it should ask the user "Would you like to re-enter your SSN? where they answer y or n the only issue is that when they answer, it continues to say ""DDD-DD-DDDD" is not a valid SSN". Is this an issue of the mass of if/else if/for/while statements I have?
Thanks.
Upvotes: 0
Views: 270
Reputation: 140494
The for loop is quite unnecessary and makes it all a lot more verbose. If you really can't use a regex, just hard-code the conditions on each character:
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();
}
Upvotes: 0
Reputation: 88737
You should query the user for the ssn at the start of the loop, i.e. put String ssn = sc.next();
right at the top of the while-block.
Currently you are querying the user once and after the while block you reuse the value of ssn
instead of asking for a new one before validation.
Upvotes: 2