How do I implement the Luhn algorithm?

梦想与她 提交于 2019-11-29 15:32:17

The first thing I see is that you have:

int num = tmp - 0

You should instead have:

int num = tmp - '0';

Secondly, you should be validating your sum outside of the for loop, because you only care about the sum after processing all the digits.

Thirdly, you are starting from the end of the number, and you are not including the first number of your string. Why not use i for both tasks?

Resulting (working) method:

static void luhn(){
  System.out.print("Enter number to validate:\n");
  String pnr = input.nextLine();
  // 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;
  // #3: removed pos
  for (int i = 0; i < pnr.length(); i++){
    char tmp = pnr.charAt(i);
    // #1: fixed the '0' problem
    int num = tmp - '0';
    int product;
    if (i % 2 != 0){
      product = num * 1;
    }
    else{
      product = num * 2;
    }
    if (product > 9)
      product -= 9;
    sum+= product;              
  }
  // #2: moved check outside for loop
  boolean valid = (sum % 10 == 0);
  if (valid){
    System.out.print("Valid!\r");
  }
  else{
    System.out.print("Invalid!");
  }
}

Stylistically, this method would be more useful if, instead of method signature

static void luhn() {

it instead had method signature

static boolean luhn(String input) {

This easily allows your code to get the String from ANY source (a file, hardcoded, etc.) and do anything with the result (print a message as yours does, or do something else). Obviously you would move the System.out.print, input.nextLine(), and if(valid) bits of code outside of this method.

Full refactored program:

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

use org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(number)

Maven Dependency:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.5.1</version>
</dependency>

I use this function in an app for checking card number validity :

public static boolean Check(String ccNumber)
    {
            int sum = 0;
            boolean alternate = false;
            for (int i = ccNumber.length() - 1; i >= 0; i--)
            {
                    int n = Integer.parseInt(ccNumber.substring(i, i + 1));
                    if (alternate)
                    {
                            n *= 2;
                            if (n > 9)
                            {
                                    n = (n % 10) + 1;
                            }
                    }
                    sum += n;
                    alternate = !alternate;
            }
            return (sum % 10 == 0);
    }

Hope it helps,

You should be subtracting '0' from tmp, not 0. Subtracting 0 returns the ASCII value, which you don't want.

Here's some functions I wrote to both calculate the check digit for a given number and to verify a given number sequence and extract the number from it.

To calculate the check digit for a given number:

/**
 * Generates the check digit for a number using Luhn's algorithm described in detail at the following link:
 * https://en.wikipedia.org/wiki/Luhn_algorithm
 *
 * In short the digit is calculated like so:
 * 1. From the rightmost digit moving left, double the value of every second digit. If that value is greater than 9,
 *    subtract 9 from it.
 * 2. Sum all of the digits together
 * 3. Multiply the sum by 9 and the check digit will be that value modulo 10.
 *
 * @param number the number to get the Luhn's check digit for
 * @return the check digit for the given number
 */
public static int calculateLuhnsCheckDigit(final long number) {
    int     sum       = 0;
    boolean alternate = false;
    String  digits    = Long.toString(number);

    for (int i = digits.length() - 1; i >= 0; --i) {
        int digit = Character.getNumericValue(digits.charAt(i)); // get the digit at the given index
        digit = (alternate = !alternate) ? (digit * 2) : digit;  // double every other digit
        digit = (digit > 9)              ? (digit - 9) : digit;  // subtract 9 if the value is greater than 9
        sum += digit;                                            // add the digit to the sum
    }

    return (sum * 9) % 10;
}

To verify a sequence of digits using Luhn's algorithm and extract the number:

/**
 * Verifies that a given number string is valid according to Luhn's algorithm, which is described in detail here:
 * https://en.wikipedia.org/wiki/Luhn_algorithm
 *
 * In short, validity of the number is determined like so:
 * 1. From the rightmost digit (the check digit) moving left, double the value of every second digit. The check
 *    digit is not doubled; the first digit doubled is the one immediately to the left of the check digit. If that
 *    value is greater than 9, subtract 9 from it.
 * 2. Sum all of the digits together
 * 3. If the sum modulo 10 is equal to 0, then the number is valid according to Luhn's algorithm
 *
 * @param luhnsNumber the number string to verify and extract the number from
 * @return an empty Optional if the given string was not valid according to Luhn's algorithm
 *         an Optional containing the number verified by Luhn's algorithm if the given string passed the check
 */
public static Optional<Long> extractLuhnsNumber(final String luhnsNumber) {
    int     sum       = 0;
    boolean alternate = true;
    Long    number    = Long.parseLong(luhnsNumber.substring(0, luhnsNumber.length() - 1));

    for (int i = luhnsNumber.length() - 1; i >= 0; --i) {
        int digit = Character.getNumericValue(luhnsNumber.charAt(i)); // get the digit at the given index
        digit = (alternate = !alternate) ? (digit * 2) : digit;       // double every other digit
        digit = (digit > 9)              ? (digit - 9) : digit;       // subtract 9 if the value is greater than 9
        sum += digit;                                                 // add the digit to the sum
    }

    return (sum % 10 == 0) ? Optional.of(number) : Optional.empty();
}

Newcomers to this post/question can check appropriate Wikipedia page for solution. Below is the Java code copy-pasted from there.

public class Luhn
{
        public static boolean check(String ccNumber)
        {
                int sum = 0;
                boolean alternate = false;
                for (int i = ccNumber.length() - 1; i >= 0; i--)
                {
                        int n = Integer.parseInt(ccNumber.substring(i, i + 1));
                        if (alternate)
                        {
                                n *= 2;
                                if (n > 9)
                                {
                                        n = (n % 10) + 1;
                                }
                        }
                        sum += n;
                        alternate = !alternate;
                }
                return (sum % 10 == 0);
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!