Luhn在Java中的公式实现

时间:2015-03-23 06:59:47

标签: java credit-card luhn

我正在尝试在我的java servlet应用程序中实现一个luhn公式。我尝试在互联网上散布的其他“有效”信用卡号码并没有奏效。我只是想知道我是否正确。任何帮助都是适合的!

    public static boolean luhn(String input){
         char[] creditCard  = input.toCharArray();
         int checkSum = 0;
         boolean alternate = false;

         for (int i = creditCard.length - 1; i >= 0; i --){
              int m = (int)Integer.parseInt(Character.toString(creditCard[i]));
              if (alternate){
                  m *= 2;
                  if (m > 9){
                     m = (m & 10) + 1;
                  }
             }
        checkSum += m;
        alternate = true;
    }

    if ( (checkSum % 10) == 0){
        return true;
    }else{
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

这里是工作代码

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);

}

检查luhn algo

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;

}

或更折射的程序可能如下所示

import java.util.Scanner;
public class Luhn {
private static Scanner input;

public static void main(String... args) {
input = new Scanner(System.in);
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
boolean result = luhn(pnr);
printMessage(result);
input.close();
}

static boolean luhn(String pnr){
// this only works if you are certain all input will be at least 10   characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
  throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
for (int i = 0; i < pnr.length(); i++){
  char tmp = pnr.charAt(i);
  int num = tmp - '0';
   int product;
   if (i % 2 != 0){
     product = num * 1;
   }
   else{
    product = num * 2;
  }
   if (product > 9)
    product -= 9;
   sum+= product;              
 }
  return (sum % 10 == 0);
 }

 private static void printMessage(boolean valid) {
  if (valid){
  System.out.print("Valid!\r");
  }
  else{
  System.out.print("Invalid!");
 }
 }
}