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