Open clayjh opened 5 years ago
Try this :
package com.journaldev.util;
public class JavaLuhnAlgorithm {
public static void main(String[] args) { validateCreditCardNumber("12345678903555"); String imei = "012850003580200"; validateCreditCardNumber(imei); }
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
} }
Or try this:
public static boolean checkCreditCard(String cc) { final boolean[] dbl = {false}; return cc .replaceAll("\s+", "") .chars() .map(c -> Character.digit((char) c, 10)) .map(i -> ((dbl[0] = !dbl[0])) ? (((i2)>9) ? (i2)-9 : i*2) : i) .sum() % 10 == 0; }
The luhn algorithm has to start from the furthest right of the card number. I would reverse the string before you set n