JKawa JKawa - 3 months ago 28
Java Question

Extracting each digit in an int

So I'm in a process of writing a small encrypter program. I start by asking the user to enter a 4 digit number (>= 1000 and <= 9999). I'd like to extract each digit from the number entered by the user, and store them in a variable.

My assignment gives me hint which doesn't help me much (Hint: integer division and the modulus might be useful here).


The "hint" is actually a nearly direct explanation of how to do what you need to do: dividing in integers by ten gets rid of the last digit, while obtaining modulo ten gives you the last digit:

int x = 12345;
int lastDigit = x % 10;       // This is 5
int remainingNumber = x / 10; // This is 1234

Do this in a loop until the remaining number is zero. This gives you digits of the number in reverse.