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);
}
}
Basically you need two steps instead of one:
10^X
to remove the last X
digits. (N / 10^X
)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));
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With