Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement the Luhn algorithm?

I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid even though they're not.

This number should be valid, but my code doesn't think so: 8112189876

This number should not be valid, which my program agrees with, as it thinks every number is invalid: 8112189875

Here is my code:

static void luhn(){
    System.out.print("Enter number to validate:\n");
    String pnr = input.nextLine();
    int length = pnr.length();
    int sum = 0;
    for (int i = 1, pos = length - 1; i < 10; i++, pos--){
        char tmp = pnr.charAt(pos);
        int num = tmp - 0
        int product;
        if (i % 2 != 0){
            product = num * 1;
        }
        else{
            product = num * 2;
        }
        if (product > 9)
            product -= 9;
        sum+= product;              
        boolean valid = (sum % 10 == 0);
        if (valid){
            System.out.print("Valid!\r");
        }
        else{
            System.out.print("Invalid!");
        }
    }
}
like image 572
Pontus Avatar asked Nov 28 '22 09:11

Pontus


1 Answers

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>
like image 50
Bharat Pahalwani Avatar answered Dec 05 '22 17:12

Bharat Pahalwani