Formatting SSN with String.format

I am currently using a random generator for generator numbers for 9 digits. I am currently trying to use String.format in java to print random numbers like XXX-XX-XXXX, which looks like a social security number. I just can't do it, and I'm not sure how to do it. I use modulo, and it seems that my add-ons are disabled, or I'm just completely wrong. The problem is that I have to use modulo. Any help sent me in the right direction is greatly appreciated, thanks. I am trying to set 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); } } 
+5
source share
2 answers

Try to do

 return String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ", firstName, lastName,(int)ID/1000000,(int)(ID%1000000)/10000, ID%10000); 
+4
source

Basically you need two steps instead of one:

  • Divide the number by 10^X to delete the last digits of X ( N / 10^X )
  • Get modulo number 10^Y to take the last digits of Y ( 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 out the appropriate fragments

 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)); } 
+5
source

Source: https://habr.com/ru/post/1263553/


All Articles