Search code examples
javaluhn

Making Luhn's Check Digit - Java


I've been trying to make a check digit in java using the Luhn algorithm and I've come here out of total frustration. I am in the very first step, which is summing all of the digits together (with every second digit doubled and subtracted by 9 if it becomes greater than 9 after doubling) yet I cannot get an answer anywhere near what the sum is supposed to be. If I were to enter "11" as the string, the output sum comes out as 138 when it should be 3. I have no clue what is wrong in my code and I'm wondering if someone with more experience could help me.

    import javax.swing.JOptionPane;
    public class Assignment
    {    public static void main (String []args)
{
    String UserNum;
    char c;
    int secondnum, ctwo;
    secondnum = 0;
    ctwo = 0;
    UserNum = JOptionPane.showInputDialog("Please enter a number: ");
    int len, i;
    len = UserNum.length();
    i = 0;
    System.out.println(UserNum);
    while (i < len) {
        c = UserNum.charAt(i);
        System.out.println(c);
        i++;
        if (i%2==0){
            ctwo = c*2;
            if (ctwo > 9) { 
                ctwo = ctwo - 9;
                secondnum = secondnum + ctwo;
            }
            else { secondnum = secondnum + ctwo;
            }
}
else {
    secondnum = secondnum + c;
    }
    System.out.println(secondnum);
        }
    }
    }

Addition: Even after simplifying the code down to just adding the values of each separate digit together, the sum of said values is still far off.


Solution

  • You are using each digit's ASCII value instead of the digit itself. Since ASCII codes are sequential, it's pretty easy to extract the numerical value - just subtract '0':

    c = UserNum.charAt(i) - '0'; // Note that c must be defined as an int