【问题标题】:Validate credit card details验证信用卡详细信息
【发布时间】:2012-01-17 13:36:46
【问题描述】:

如何验证信用卡。我需要做 luhn 检查。黑莓中是否有api可以做到这一点?

【问题讨论】:

    标签: java validation


    【解决方案1】:

    您可以使用以下方法验证信用卡号

    // -------------------
    // Perform Luhn check
    // -------------------
    
    public static boolean isCreditCardValid(String cardNumber) {
        String digitsOnly = getDigitsOnly(cardNumber);
        int sum = 0;
        int digit = 0;
        int addend = 0;
        boolean timesTwo = false;
    
        for (int i = digitsOnly.length() - 1; i >= 0; i--) {
            digit = Integer.parseInt(digitsOnly.substring(i, i + 1));
            if (timesTwo) {
                addend = digit * 2;
                if (addend > 9) {
                    addend -= 9;
                }
            } else {
                addend = digit;
            }
            sum += addend;
            timesTwo = !timesTwo;
        }
    
        int modulus = sum % 10;
        return modulus == 0;
    
    }
    

    【讨论】:

    【解决方案2】:
    using System; 
    
    class GFG { 
    
    // Returns true if given 
    // card number is valid 
    static bool checkLuhn(String cardNo) 
    { 
        int nDigits = cardNo.Length; 
        int nSum = 0; 
        bool isSecond = false; 
        for (int i = nDigits - 1; i >= 0; i--) 
        { 
            int d = cardNo[i] - '0'; 
            if (isSecond == true) 
                d = d * 2; 
    
            // We add two digits to handle 
            // cases that make two digits 
            // after doubling 
            nSum += d / 10; 
            nSum += d % 10; 
            isSecond = !isSecond; 
        } 
        return (nSum % 10 == 0); 
    } 
    
        static public void Main() 
        { 
            String cardNo = "79927398713"; 
            if (checkLuhn(cardNo)) 
                Console.WriteLine("This is a valid card"); 
            else
                Console.WriteLine("This is not a valid card"); 
    
        } 
    } 
    

    输出:-

    这是一张有效的卡片

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2011-09-24
      • 2014-02-05
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2020-09-28
      相关资源
      最近更新 更多