Advice, writing a social security code

2019-10-02 06:11发布

Im new to java and my class we need to write a program where the user inputs there social security code in the form of XXXXXXXXX and it returns it in the form of XXXX-XX-XXX. For example if there code was 123456789 it would be returned to them as 123-45-6789.

Here is what I have, I would like to use substrings to finish it off.

import java.util.Scanner;

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

    String name;
    int ssn;
    System.out.print ("Enter nine digit social security number without dashes: ");
    ssn= reader.nextInt();
    System.out.print("Your formatted social security number is: ");
    System.out.println(snn.substring(,) );

   }
   }

This is the new code

import java.util.Scanner;

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

    String name;
    String Ssn="ssn";

    System.out.print ("Enter nine digit social security number without dashes: ");
    Ssn= reader.nextLine();
    System.out.print("Your formatted social security number is: ");
    System.out.println (Snn.substring(0,3) +"-"snn.substring(4,6) + "-"snn.substring(7,9);

}
}

1条回答
forever°为你锁心
2楼-- · 2019-10-02 06:28

Actually a more appropriate way to do this would be to use a Matcher with a Pattern representing a regex containing the subgroups of the social security number as capturing groups:

final Pattern ssnFormat = Pattern.compile("^(\\d{3})(\\d{2})(\\d{4})$");

Matcher m = ssnFormat.matcher(ssn);  // make ssn a string!

if (m.find()) {
    System.out.printf("%s-%s-%s%n", m.group(1), m.group(2), m.group(3));
} else {
    System.err.println("Enter a valid social security number!");
}

As noted, a social security number, while representable as an integer, is really a string of digits: it's meaningless as a number. Therefore, you should store it as a String and not as an int.


Now, in your new code, you're almost there, but still have a few issues:

  • It's String, not string.
  • Now that ssn is a string, you can't assign it to the result of reader.nextInt(), since that returns an int. Instead, you'll want to use reader.nextLine().
  • The ranges of the second and third substring() calls are slightly off. Refer to the method's documentation.
查看更多
登录 后发表回答