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

时间:2020-03-02 17:01:09

标签: java string int

我有一个作业,要求用户输入一个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);
    }
}

}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以尝试计算破折号的数量,以断定有两个。然后,尝试解析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
}

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