Comparing strings to ints in Java

efan :

I have an assignment asking the user to enter a SSN and the program tells whether or not it's valid. I got the base of the program working, but at this point, the user can enter numbers as well as letters and I'm not sure how to fix that. I know about parseInt, but I couldn't figure out how to work it since the input has dashes in it. My professor also told us we can't use loops since there's no need to.

import java.util.Scanner;

public class Exercise04_21 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // DDD-DD-DDDD
    System.out.print("Enter a SSN: ");
    String ssn = input.next();


    if (ssn.charAt(3) == '-' && ssn.charAt(6) == '-') {
        if (ssn.length() == 11) {
            System.out.printf("%s is a valid social security number", ssn);
        } else {
            System.out.printf("%s is an invalid social security number", ssn);
        }
    } else {
        System.out.printf("%s is not a valid social security number", ssn);
    }
}

}

Tim Biegeleisen :

You could try to count the number of dashes, to assert that there are two. Then, try parsing the SSN input with dashes removed as an integer. Should that parse operation not throw an exception, then the input is valid.

String ssn = input.next();
int numDashes = ssn.length() - ssn.replace("-", "").length();
boolean canParse = true;

try {
    int ssnInt = Integer.parseInt(ssn.replace("-", ""));
}
catch (NumberFormatException nfe) {
    canParse = false;
}

if (numDashes == 2 && canParse) {
    System.out.printf("%s is a valid social security number", ssn);
}
else {
    System.out.printf("%s is an invalid social security number", ssn);
}

Of course, you could also make life easy by just using a regular expression:

if (ssn.matches("\\d{3}-\\d{2}-\\d{4}")) {
    // VALID
}

But, perhaps your assignment does not allow for using regular expressions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20792&siteId=1