Search code examples
javacredit-cardluhn

Luhn formula implementation in Java


I'm trying to implement a luhn formula in my java servlet application. I tried other 'valid' credit cards numbers scattering in the internet and didn't work. I just want to know if I got it correctly. Any help would be appreaciate!

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

Solution

  • here the working code

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

    }

    to check for 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;
    

    }

    or a more refracted program might be as below

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