Advertisement
Guest User

Untitled

a guest
Jun 15th, 2013
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. /**
  2. * Validates a credit card numer.
  3. * @author Apache Ah64
  4. */
  5. public class CreditCardValidator {
  6.  
  7. /**
  8. * The credit card numbers.
  9. */
  10. private static final String[] CC_CARDS = new String[] {
  11. "378282246310005",
  12. "371449635398431",
  13. "378734493671000",
  14. "5610591081018250",
  15. "30569309025904",
  16. "38520000023237",
  17. "6011111111111117",
  18. "6011000990139424",
  19. "3530111333300000",
  20. "3566002020360505",
  21. "5555555555554444",
  22. "5105105105105100",
  23. "4111111111111111",
  24. "4012888888881881",
  25. "4222222222222",
  26. "4417123456789113"
  27. };
  28.  
  29. /**
  30. * The main method.
  31. * @param args The arguments.
  32. */
  33. public static void main(String[] args) {
  34. for(int i = 0; i < CC_CARDS.length; i++) {
  35. final String number = CC_CARDS[i];
  36. System.out.println("Credit card number: "+number+" is "+(!isValid(number.toCharArray()) ? "in" : "")+"valid");
  37. }
  38. }
  39.  
  40. /**
  41. * Check for a valid credit card number.
  42. * @param number The credit card number.
  43. * @return If the credit card number is valid {@code true}.
  44. */
  45. private static boolean isValid(char[] numbers) {
  46. int sum = 0, len = numbers.length, d, i;
  47. final boolean div_two_z = len % 2 == 0;
  48. for (i = len - 1; i >= 0; i--) {
  49. d = (numbers[i] - '0') * ((div_two_z ? i % 2 == 0 : i % 2 != 0) ? 2 : 1);
  50. sum += d > 9 ? d / 10 + d % 10 : d;
  51. }
  52. return sum % 10 == 0;
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement