Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

java - Advice, writing a social security code

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

}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...