将字符串与 Java 中的整数进行比较

Comparing strings to ints in Java

我有一个作业要求用户输入 SSN,程序会告诉它是否有效。我得到了程序的基础工作,但在这一点上,用户可以输入数字和字母,我不确定如何解决这个问题。我知道 parseInt,但我不知道如何使用它,因为输入中有破折号。我的教授还告诉我们不能使用循环,因为没有必要。

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);
    }
}

}

您可以对类似的内容使用正则表达式。 例如:

String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$";
Pattern pattern = Pattern.compile(regex);
boolean matches = Pattern.matches(pattern, text);

您可以尝试计算破折号的数量,以断言有两个破折号。然后,尝试将去掉破折号的 SSN 输入解析为整数。如果该解析操作没有抛出异常,则输入有效。

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);
}

当然,你也可以通过使用正则表达式来简化生活:

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

但是,也许您的作业不允许使用正则表达式。