I need to write a Java program that validates credit card numbers, and to do that I need to preform operations on each individual digit. How can I get these digits, without using strings or arrays?
Asked
Active
Viewed 3,743 times
-3
-
Why don't you want to use strings or arrays? That's pretty much the only reasonable way to do it... – tckmn Oct 23 '13 at 21:03
-
For the purpose of the assignment, we are not allowed to use arrays or string operations. We either need to get each number and store it as a variable, or somehow perform the required checks in a loop, which I have no clue how to do. – Bottlecaps Oct 23 '13 at 21:05
-
We are required to take the input as a long – Bottlecaps Oct 23 '13 at 21:07
-
@Spork Whoops, I was wrong :> – user2864740 Oct 23 '13 at 21:08
2 Answers
2
int number; (This would be your credit card number)
while (number > 0) {
System.out.println( number % 10);
number = number / 10;
}
This will print them in reverse order. You can perform your operations on the digits this way.

Zach Winkler
- 234
- 4
- 6
-
ahem! int will not be big enough to hold 16 digits. But well done for taking the time to code it. – Bathsheba Oct 23 '13 at 21:07
-
Once I have the numbers I need to be able to preform operations on them. More specifically, every second number needs to be multiplied by 2, then if it is greater than 9 9 must be subtracted from it. Then all numbers must be summed up, and if the total % 10 = 0 it is a valid number. – Bottlecaps Oct 23 '13 at 21:10
-
@Spork So do that, one digit at a time (e.g. `int digit = number % 10`). Another variable can be used to track even/odd digits and another one to store the running sum. – user2864740 Oct 23 '13 at 21:10
-
@Spork So, you are basically just trying to implement [this](http://en.wikipedia.org/wiki/Luhn_algorithm). – tckmn Oct 23 '13 at 21:11
-
Yes, it is essentially just that algorithm. I'm not sure how to apply the operations, especially the -9, inside a while or for loop though. – Bottlecaps Oct 23 '13 at 21:12
0
Assuming you're using a 64 bit integral type (which is sufficient for a 16 digit card number), a long
will do the trick; e.g. long num
.
use num % 10
to extract the rightmost digit.
use num / 10
to remove the rightmost digit.
That's all you need to do (in a loop structure obviously), but why do it like this anyway? Do a good job instead. Use http://en.wikipedia.org/wiki/Luhn_algorithm with which credit card numbers comply.

Bathsheba
- 231,907
- 34
- 361
- 483