Formatting SSN using String.format
Asked Answered
B

2

5

I am currently using a random genertor to generator numbers 9 digit numbers for me. I am currently trying to use String.format, in java, to print the random numbers like this XXX-XX-XXXX which is like a social security number. I simply cant do it and i not sure how to do. I am using modulo and it seems my padding are off or i am just completely wrong. The issues is that i have to use modulo. Any assistance pointing me to the right direction is much appreciated, thank you. I am trying to fix the ID.

public  String toString (){

        System.out.printf("%d\n",ID);

        return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ", firstName, lastName,ID%1000,ID%10000, ID%000001000);

    }
}
Biocellate answered 29/1, 2017 at 23:56 Comment(2)
Use decimal format class javaFlaccid
In your source code you must not have numbers that start with 0. Your number 00001000 is not 1000, but 512. Read something about octal numbers to find out why.Escallop
Z
5

Try doing

return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ", firstName, lastName,(int)ID/1000000,(int)(ID%1000000)/10000, ID%10000);
Zoophyte answered 30/1, 2017 at 0:3 Comment(3)
That Worked. Can you please explain why did you have to cast it with int?Biocellate
I wasn't sure if ID was an integer, so I added it to be safe. If it was a double %0xd would need to be %0xfZoophyte
Ok it was a int first, but you just added knowledge to my java programming. thank you so much.Biocellate
A
5

Basically you need two steps instead of one:

  1. Divide the number by 10^X to remove the last X digits. (N / 10^X)
  2. Get the number modulo 10^Y to take the last Y digits. (N % 10^Y)

Modified Code

public static int getDigits(int num, int remove, int take) {
    return (num / (int)Math.pow(10, remove)) % (int)Math.pow(10, take);
}

public String toString() {
    return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ",
                          firstName, lastName,
                          getDigits(ID, 6, 3), getDigits(ID, 4, 2), getDigits(ID, 0, 4));
}

Alternative Solution

Convert the number to String and use String.substring to cut the relevant pieces

public String toString() {
    String IdStr = String.valueOf(ID);
    return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ",
                          firstName, lastName,
                          IdStr.substring(0, 3), IdStr.substring(3, 5), IdStr.substring(5, 9));
}
Annelid answered 30/1, 2017 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.