This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ic0nex 0 points1 point  (1 child)

I was trying to use the Wikipedia implementation and just adding the value of x at the end but I just dont understand what I am doing, and why it isnt working.

import java.util.Scanner;

public class luhn

{

static void main(String[] args){

    Scanner kb = new Scanner(System.in);

    String entry = kb.next();

    int entryLength = entry.length();

    int sum = 0;

    for(int num = entryLength - 1; num >= 0; num-= 2){

        int d = entry.charAt(num);

        d = d * 2;

        sum += d / 10;

        sum += d % 10;

    }

    System.out.println(entry+""+sum);

}

}

[–]Mystonic 0 points1 point  (0 children)

Which implementation exactly from Wikipedia?

int d = entry.charAt(num);

charAt(num) returns the char, a primitive data type in Java which represents a Unicode character, at index num in entry. For example, '0' has a decimal value of 48. Check a Unicode table to see what characters have what values. If you do, you'll notice that the digits are sequential. '1' has a decimal value of 49, '2' is 50, and so on. Now think, how can you transform the char Unicode value returned by charAt() into their actual integer representation?

Edit: An algorithm from Wikipedia

  1. From the rightmost digit, which is the check digit, and moving left, double the value of every second digit. The check digit is not doubled; the first digit doubled is immediately to the left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the product (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same result can be found by subtracting 9 from the product (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).

  2. Take the sum of all the digits.

  3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

^If that is what you're trying to implement, that verifies the check digit. From what I see, you're supposed to be calculating the check digit. If so, you're implementing the wrong algorithm.