Check Credit Card Validity using Luhn Algorithm

前端 未结 12 1566
刺人心
刺人心 2020-12-03 04:02

I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:

  1. Double every second digit from right to left. If do

相关标签:
12条回答
  • 2020-12-03 04:14

    You can freely import the following code:

    public class Luhn
    {
        public static boolean Check(String ccNumber)
        {
                int sum = 0;
                boolean alternate = false;
                for (int i = ccNumber.length() - 1; i >= 0; i--)
                {
                        int n = Integer.parseInt(ccNumber.substring(i, i + 1));
                        if (alternate)
                        {
                                n *= 2;
                                if (n > 9)
                                {
                                        n = (n % 10) + 1;
                                }
                        }
                        sum += n;
                        alternate = !alternate;
                }
                return (sum % 10 == 0);
        }
    }
    

    Link reference: https://github.com/jduke32/gnuc-credit-card-checker/blob/master/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java

    0 讨论(0)
  • 2020-12-03 04:14

    this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number

    if(ccnum.length()==16){
        char[] c = ccnum.toCharArray();
        int[] cint = new int[16];
        for(int i=0;i<16;i++){
            if(i%2==1){
                cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
                if(cint[i] >9)
                    cint[i]=1+cint[i]%10;
            }
            else
                cint[i] = Integer.parseInt(String.valueOf(c[i]));
        }
        int sum=0;
        for(int i=0;i<16;i++){
            sum+=cint[i];
        }
        if(sum%10==0)
            result.setText("Card is Valid");
        else
            result.setText("Card is Invalid");
    }else
        result.setText("Card is Invalid");
    

    If you want to make it use on any number replace all 16 with your input number length.

    It will work for Visa number given in the question.(I tested it)

    0 讨论(0)
  • 2020-12-03 04:14

    Here is the implementation of Luhn algorithm.

    public class LuhnAlgorithm {
    
    /**
     * Returns true if given card number is valid
     *
     * @param cardNum Card number
     * @return true if card number is valid else false
     */
    private static boolean checkLuhn(String cardNum) {
        int cardlength = cardNum.length();
        int evenSum = 0, oddSum = 0, sum;
        for (int i = cardlength - 1; i >= 0; i--) {
            System.out.println(cardNum.charAt(i));
            int digit = Character.getNumericValue(cardNum.charAt(i));
            if (i % 2 == 0) {
                int multiplyByTwo = digit * 2;
                if (multiplyByTwo > 9) {
                    /* Add two digits to handle cases that make two digits after doubling */
                    String mul = String.valueOf(multiplyByTwo);
                    multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
                }
                evenSum += multiplyByTwo;
            } else {
                oddSum += digit;
            }
        }
        sum = evenSum + oddSum;
        if (sum % 10 == 0) {
            System.out.println("valid card");
            return true;
        } else {
            System.out.println("invalid card");
            return false;
        }
    
    }
    
    public static void main(String[] args) {
        String cardNum = "4071690065031703";
        System.out.println(checkLuhn(cardNum));
    }
    
    }
    
    0 讨论(0)
  • 2020-12-03 04:17

    Google and Wikipedia are your friends. Instead of long-array I would use int-array. On Wikipedia following java code is published (together with detailed explanation of Luhn algorithm):

       public static boolean check(int[] digits) {
         int sum = 0;
         int length = digits.length;
         for (int i = 0; i < length; i++) {
    
           // get digits in reverse order
           int digit = digits[length - i - 1];
    
           // every 2nd number multiply with 2
           if (i % 2 == 1) {
               digit *= 2;
           }
           sum += digit > 9 ? digit - 9 : digit;
         }
         return sum % 10 == 0;
       }
    

    You should work on your input processing code. I suggest you to study following solution:

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean repeat;
        List<Integer> digits = new ArrayList<Integer>();
    
        do {
            repeat = false;
            System.out.print("Enter your Credit Card Number : ");
            String input = in.next();
    
            for (int i = 0; i < input.length(); i++) {
                char c = input.charAt(i);
                if (c < '0' || c > '9') {
                    repeat = true;
                    digits.clear();
                    break;
                } else {
                    digits.add(Integer.valueOf(c - '0'));
                }
            }
        } while (repeat);
    
        int[] array = new int[digits.size()];
        for (int i = 0; i < array.length; i++) {
            array[i] = Integer.valueOf(digits.get(i));
        }
        boolean valid = check(array);
        System.out.println("Valid: " + valid);
    }
    
    0 讨论(0)
  • 2020-12-03 04:20

    I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:

    array[] = {1, 2, 3, 4, 5}
    

    Since you already have the digits, in sumOfOddPlace you should do something like

    public static int sumOfOddPlace(long[] array) {
        int result = 0;
        for (int i = 1; i < array.length; i += 2) {
            result += array[i];
        }
        return result;
    }
    

    And in sumOfDoubleEvenPlace:

    public static int sumOfDoubleEvenPlace(long[] array) {
        int result = 0;
        for (int i = 0; i < array.length; i += 2) {
            result += getDigit(2 * array[i]);
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-03 04:22

    I took a stab at this with Java 8:

    public static boolean luhn(String cc) {
        final boolean[] dbl = {false};
        return cc
                .chars()
                .map(c -> Character.digit((char) c, 10))
                .map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
                .sum() % 10 == 0;
    }
    

    Add the line

                .replaceAll("\\s+", "")
    

    Before

                .chars()
    

    If you want to handle whitespace.

    Seems to produce identical results to

    return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
    

    From Apache's commons-validator.

    0 讨论(0)
提交回复
热议问题