Sunday, December 14, 2014

Luhn Algorithm With Java

Luhn Algorithm is a method to check the validation of Credit Card.
Almost all credit card in the world using this method for generating card number.

This is my implementation using Java:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class LuhnValidator {
    public static boolean isValidCardNumber(String cardNumber) {
        if(cardNumber==null) return false;

        cardNumber = cardNumber.trim();
        if(cardNumber.equals("")) return false;

        int res = 0;
        boolean odd=true;
        for(int i=cardNumber.length()-1;>=0;i--) {
            char c = cardNumber.charAt(i);
            if(c>='0' && c<='9') {
                int v = c - '0';
                if(!odd) {
                    v *= 2;
                    v = (v/10) + (v%10);
                }
                odd = !odd;
                res += v;
            }
            // skip space
            else if(c!=' ') {
                // other character is not valid
                return false;
            }
        }
        return (res%10) == 0;
    }

    public static void main(String []args) {
        System.out.println(LuhnValidator.isValidCardNumber(null));
        System.out.println(LuhnValidator.isValidCardNumber(" "));
        System.out.println(LuhnValidator.isValidCardNumber("4111 1111 1111 1111"));
        System.out.println(LuhnValidator.isValidCardNumber("4124123143215674"));
        System.out.println(LuhnValidator.isValidCardNumber("4184126643215675"));
    }
}

1 comment: