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);
}
}
Actually a more appropriate way to do this would be to use a
Matcher
with aPattern
representing a regex containing the subgroups of the social security number as capturing groups: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 anint
.Now, in your new code, you're almost there, but still have a few issues:
String
, notstring
.ssn
is a string, you can't assign it to the result ofreader.nextInt()
, since that returns anint
. Instead, you'll want to usereader.nextLine()
.substring()
calls are slightly off. Refer to the method's documentation.