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);
}
Boann
  • 48,794
  • 16
  • 117
  • 146
Hannah P
  • 89
  • 4
  • 3
    What made you think you went wrong? Do you get an error? Unexpected results? Please add details, and the output you get – Guillaume Oct 07 '11 at 13:07

3 Answers3

7

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

boolean alternateNum = false;
Boann
  • 48,794
  • 16
  • 117
  • 146
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;
  }
Lyth
  • 2,171
  • 2
  • 29
  • 37
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;
    ...
}
Waylon Flinn
  • 19,969
  • 15
  • 70
  • 72