Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Validates a credit card numer.
- * @author Apache Ah64
- */
- public class CreditCardValidator {
- /**
- * The credit card numbers.
- */
- private static final String[] CC_CARDS = new String[] {
- "378282246310005",
- "371449635398431",
- "378734493671000",
- "5610591081018250",
- "30569309025904",
- "38520000023237",
- "6011111111111117",
- "6011000990139424",
- "3530111333300000",
- "3566002020360505",
- "5555555555554444",
- "5105105105105100",
- "4111111111111111",
- "4012888888881881",
- "4222222222222",
- "4417123456789113"
- };
- /**
- * The main method.
- * @param args The arguments.
- */
- public static void main(String[] args) {
- for(int i = 0; i < CC_CARDS.length; i++) {
- final String number = CC_CARDS[i];
- System.out.println("Credit card number: "+number+" is "+(!isValid(number.toCharArray()) ? "in" : "")+"valid");
- }
- }
- /**
- * Check for a valid credit card number.
- * @param number The credit card number.
- * @return If the credit card number is valid {@code true}.
- */
- private static boolean isValid(char[] numbers) {
- int sum = 0, len = numbers.length, d, i;
- final boolean div_two_z = len % 2 == 0;
- for (i = len - 1; i >= 0; i--) {
- d = (numbers[i] - '0') * ((div_two_z ? i % 2 == 0 : i % 2 != 0) ? 2 : 1);
- sum += d > 9 ? d / 10 + d % 10 : d;
- }
- return sum % 10 == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement