我有一个作业要求用户输入 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);
}
}
}
最佳答案
您可以尝试计算破折号的数量,以断言有两个。然后,尝试将删除破折号的 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
}
但是,也许您的作业不允许使用正则表达式。
关于java - Java 中字符串与整数的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60493454/