我有一个用户输入他们的社会安全号码(假号码),我需要它的格式为111-11-1111,包括短划线。如果用户输入没有破折号的信息,或超过999-99-9999,程序会提示用户输入正确的信息。这是我的代码,我该如何解决这个问题?另外,我可以使用StringBuilder
作为其中的任何部分吗?
import java.util.Scanner;
import java.lang.StringBuilder;
import java.lang.Math;
class TaxReturn
{
public static void main(String[] args)
{
String firstName, mI, lastName;
char M;
char S;
int SSN;
final int SSNLimit = 999999999;
int zip;
int income;
int pets;
int vehicle;
int toaster;
//Start string firstName
Scanner inputDevice = new Scanner(System.in);
System.out.print("First name: ");
firstName = inputDevice.next();
//Start middle name
System.out.print("Middle initial: ");
mI = inputDevice.next();
//Start lastName
System.out.print("Last name: ");
lastName = inputDevice.next();
//Start SSN (Social Security Number)
System.out.print("What is your Social Security Number?: ");
SSN = inputDevice.nextInt();
while(SSN > SSNLimit)
{
System.out.print("Invalid entry, please enter a valid Social Security Number");
System.out.print("\nPlease enter your Social again:");
SSN = inputDevice.nextInt();
}
}
}
答案 0 :(得分:0)
由于您接受ssn作为整数,您可以检查数字范围,即9位数范围,并可以执行以下操作:
final int ssnEndLimit = 999999999;
final int ssnStartLimit = 100000000;
while(SSN > ssnEndLimit || SSN < ssnStartLimit) {//if its not 9 digits exactly
...
}
//Now Format as per OP's requirement
String formattedSSN = formatSSN(SSN);
private static String formatSSN(int ssn) {
DecimalFormat ssnDecimalFmt = new DecimalFormat("000000000");
String ssnRawString = ssnDecimalFmt.format(ssn);
MessageFormat ssnMsgFmt = new MessageFormat("{0}-{1}-{2}");
String[] ssnNumArr = {ssnRawString.substring(0, 3), ssnRawString.substring(3, 5), ssnRawString.substring(5)};
return ssnMsgFmt.format(ssnNumArr));
}
答案 1 :(得分:0)
您正在使用nextInt()来读取值。但在你的情况下,它不是一个整数值,因为它包含&#34; - &#34;。因此,将输入用作字符串然后应用正则表达式来检查输入的字符串是否为有效格式。
对于SSN的匹配,您可以使用正则表达式
String pattern = "^\d{3}-\d{2}-\d{4}$";
// Create a Pattern object
Pattern ssnPattern = Pattern.compile(pattern);
SSN = inputDevice.next();
// Now create matcher object.
Matcher m = ssnPattern.matcher(SSN);
if(m.matches()){
//valid
}else{
// invalid
}
或者在下面的评论中给出(在一行代码中)
if (SSN.matches("^\\d{3}-\\d{2}-\\d{4}$")){
//valid ssn
}
else {
//invalid ssn
}
但是你应该坚持第一种方法,因为它会多次执行SSN验证。 因为匹配器被预编译,因此每次代码被执行时都会重新编译string.matches
What's the difference between String.matches and Matcher.matches?
答案 2 :(得分:0)
以下是基于您的代码的修改版本。
import java.util.Scanner;
public class TaxReturn {
public static void main(String[] args) {
String firstName, mI, lastName;
char M;
char S;
int SSN;
final int SSNLimit = 999999999;
int zip;
int income;
int pets;
int vehicle;
int toaster;
// Start string firstName
Scanner inputDevice = new Scanner(System.in);
System.out.print("First name: ");
firstName = inputDevice.next();
// Start middle name
System.out.print("Middle initial: ");
mI = inputDevice.next();
// Start lastName
System.out.print("Last name: ");
lastName = inputDevice.next();
// Start SSN (Social Security Number)
System.out.print("What is your Social Security Number?: ");
while (true) {
String s = inputDevice.next();
if (s.matches("^\\d{3}-\\d{2}-\\d{4}$")) {
int i = Integer.valueOf(s.replaceAll("-", ""));
if (i < SSNLimit) {
SSN = i;
System.out.println("SSN is " + SSN);
break;
} else {
System.out.print("Invalid entry, please enter a valid Social Security Number");
System.out.print("\nPlease enter your Social again: ");
continue;
}
} else {
System.out.print("Invalid entry, please enter a valid Social Security Number");
System.out.print("\nPlease enter your Social again: ");
continue;
}
}
inputDevice.close();
}
}
答案 3 :(得分:0)
使用正则表达式可能会更好,但您也可以在没有它的情况下制定解决方案。您可能想要验证社会安全号码,如下所示:
//I put the validation inside a method to make your code easier to understand
//input should have "-", so I'm passing it as a string
public static boolean validate(String s) {
StringBuilder number = new StringBuilder(s);
if (number.charAt(3) == '-' && number.charAt(6) == '-') { //check for "-"
//if the -s is in correct indexes, remove the -s to test all other characters
number.deleteCharAt(3);
number.deleteCharAt(5);
for (int i = 0; i < number.length(); i++) { //are all other characters digits?
if (!Character.isDigit(number.charAt(i))) {
return false;
}
}
//now compute if it is over 999999999
return (Integer.parseInt(number.toString()) <= 999999999);
} else {
return false;
}
}
你可以像这样使用它:
while(!validate(SSN)) //SSN is String in this case
{
System.out.print("Invalid entry, please enter a valid Social Security Number");
System.out.print("\nPlease enter your Social again:");
SSN = inputDevice.next();
}