Last active
September 10, 2020 11:54
-
-
Save little-pinecone/c455a0db3c2053aca24dd52483df3475 to your computer and use it in GitHub Desktop.
Validate credit card numbers with the Luhn algorithm in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LuhnFormula { | |
public boolean validate(String input) { | |
char[] chars = convertToArrayOfValidChars(input); | |
return getSum(chars) % 10 == 0; | |
} | |
private char[] convertToArrayOfValidChars(String input) { | |
String sanitized = input.replaceAll("[^\\d]", ""); | |
return sanitized.toCharArray(); | |
} | |
private int getSum(char[] chars) { | |
int sum = 0; | |
for (int i = 0; i < chars.length; i++) { | |
int number = getInReverseOrder(chars, i); | |
sum += getElementValue(i, number); | |
} | |
return sum; | |
} | |
private int getInReverseOrder(char[] chars, int i) { | |
int indexInReverseOrder = chars.length - 1 - i; | |
char character = chars[indexInReverseOrder]; | |
return Character.getNumericValue(character); | |
} | |
private int getElementValue(int i, int number) { | |
if (i % 2 != 0) { | |
return getOddElementValue(number); | |
} else { | |
return number; | |
} | |
} | |
private int getOddElementValue(int element) { | |
int value = element * 2; | |
if (value <= 9) { | |
return value; | |
} | |
return value - 9; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.BeforeEach; | |
import org.junit.jupiter.api.Test; | |
import static org.junit.jupiter.api.Assertions.*; | |
class LuhnFormulaTest { | |
private LuhnFormula luhnFormula; | |
@BeforeEach | |
void setUp() { | |
luhnFormula = new LuhnFormula(); | |
} | |
@Test | |
void shouldReturnTrueForValidNumbers() { | |
assertAll( | |
() -> assertTrue(luhnFormula.validate("5277 0291 2077 3860")), | |
() -> assertTrue(luhnFormula.validate("4556-0690-9685-2293")), | |
() -> assertTrue(luhnFormula.validate("4852789106979220268")) | |
); | |
} | |
@Test | |
void shouldReturnFalseForInvalidNumbers() { | |
assertAll( | |
() -> assertFalse(luhnFormula.validate("4852 7891 0697 922 0261")), | |
() -> assertFalse(luhnFormula.validate("3543-6933-8731-4139")), | |
() -> assertFalse(luhnFormula.validate("6759310784561226")) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment