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);
}
Your code is correct except you started with the wrong alternate digit. Change to: