Posted By

Uzbekjon on 08/12/08

Statistics

Viewed 582 times
Favorited by 0 user(s)

Luhn Formula (Algorithm)

/ Published in: Java  Test harness for an implementation of the Luhn algorithm that checks the validity of a credit card number.

Copy this code and paste it in your HTML
1. /**
2.  * Test harness for an implementation of the Luhn algorithm that checks the
3.  * validity of a credit card number.
4.  */
5. public class Luhn {
6. /**
7. * Main entry point for the test harness.
8. *
9. * @param args the command line arguments.
10. */
11. public static void main(String[] args) {
12. if (args.length < 1) {
13. System.err.println("Usage: Luhn number ...");
14. System.exit(1);
15. }
16.
17. for (int i = 0; i < args.length; i++) {
18. System.out.print("Number '" + args[i] + "'" );
19. if (!args[i].matches("^\\d{13,19}\$")) {
20. System.out.println(" is not a valid credit card number (must be 13-19 digits)");
21. } else if (isValidNumber(args[i])) {
22. System.out.println(" is a valid credit card number");
23. } else {
24. System.out.println(" is not a valid credit card number");
25. }
26. }
27. }
28.
29. /**
30. * Checks whether a string of digits is a valid credit card number according
31. * to the Luhn algorithm.
32. *
33. * 1. Starting with the second to last digit and moving left, double the
34. * value of all the alternating digits. For any digits that thus become
35. * 10 or more, add their digits together. For example, 1111 becomes 2121,
36. * while 8763 becomes 7733 (from (1+6)7(1+2)3).
37. *
38. * 2. Add all these digits together. For example, 1111 becomes 2121, then
39. * 2+1+2+1 is 6; while 8763 becomes 7733, then 7+7+3+3 is 20.
40. *
41. * 3. If the total ends in 0 (put another way, if the total modulus 10 is
42. * 0), then the number is valid according to the Luhn formula, else it is
43. * not valid. So, 1111 is not valid (as shown above, it comes out to 6),
44. * while 8763 is valid (as shown above, it comes out to 20).
45. *
46. * @param number the credit card number to validate.
47. * @return true if the number is valid, false otherwise.
48. */
49. private static boolean isValidNumber(String number) {
50. int sum = 0;
51.
52. boolean alternate = false;
53. for (int i = number.length() - 1; i >= 0; i--) {
54. int n = Integer.parseInt(number.substring(i, i + 1));
55. if (alternate) {
56. n *= 2;
57. if (n > 9) {
58. n = (n % 10) + 1;
59. }
60. }
61. sum += n;
62. alternate = !alternate;
63. }
64.
65. return (sum % 10 == 0);
66. }
67. } Subscribe to comments