1

I'm trying to use this code to test if a sample code is a valid credit card number or not (using the Luhn algorithm) in Java. Where did I go wrong? It takes in an array of 16 one-digit numbers. Any help would be much appreciated. Thanks!

private static boolean isValidCC(int[] number) {
    int sum = 0;
    boolean alternateNum = true;
    for (int i = number.length-1; i>=0; i--) {
        int n = number[i];
        if (alternateNum) {
            n *= 2;
            if (n > 9) {
                n = (n % 10) + 1;
            }
        }
        sum += n;
        alternateNum = !alternateNum;
    }
    System.out.println(sum);
    return (sum % 10 == 0);
}
1
  • 3
    What made you think you went wrong? Do you get an error? Unexpected results? Please add details, and the output you get Commented Oct 7, 2011 at 13:07

3 Answers 3

7

Your code is correct except you started with the wrong alternate digit. Change to:

boolean alternateNum = false;
Sign up to request clarification or add additional context in comments.

1 Comment

You're faster :) Looks like this is the real reason.
5

Judging from Wikipedia article --you've missed a checksum digit or erroneously taking it into account--.

Update: most probably, you've started with a wrong "alternate" flag.

There is a Java snippet, so why not use it?

  public static boolean isValidCC(String number) {

    final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}};
    int sum = 0, flip = 0;

    for (int i = number.length() - 1; i >= 0; i--) {
      sum += sumTable[flip++ & 0x1][Character.digit(number.charAt(i), 10)];
    }
    return sum % 10 == 0;
  }

Comments

1

Alternating digits are doubled counting from the end not the beginning.

instead of using your alternateNum bool try this.

if((number.length - i) % 2 == 0){
    n *= 2;
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.