Java 中的 Luhn 公式实现

Luhn formula implementation in Java

我正在尝试在我的 java servlet 应用程序中实施 luhn 公式。我尝试了互联网上散布的其他 'valid' 个信用卡号码,但没有用。我只想知道我是否理解正确。任何帮助将不胜感激!

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

这里是工作代码

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 算法

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!");
 }
 }
}