欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java通过Luhn算法验证信用卡卡号是否有效,luhn信用卡,public class

来源: javaer 分享于  点击 6611 次 点评:184

Java通过Luhn算法验证信用卡卡号是否有效,luhn信用卡,public class


public class Luhn {    public static void main(String[] args) {        System.out.println(luhnTest("49927398716"));        System.out.println(luhnTest("49927398717"));        System.out.println(luhnTest("1234567812345678"));        System.out.println(luhnTest("1234567812345670"));    }    public static boolean luhnTest(String number){        int s1 = 0, s2 = 0;        String reverse = new StringBuffer(number).reverse().toString();        for(int i = 0 ;i < reverse.length();i++){            int digit = Character.digit(reverse.charAt(i), 10);            if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm                s1 += digit;            }else{//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9                s2 += 2 * digit;                if(digit >= 5){                    s2 -= 9;                }            }        }        return (s1 + s2) % 10 == 0;    }}
                                运行上面的代码,执行结果如下
truefalsefalsetrue
相关栏目:

用户点评