Skip to content

Instantly share code, notes, and snippets.

@M-ZubairAhmed
Created March 22, 2017 15:25
Show Gist options
  • Save M-ZubairAhmed/e1dd6587b8c7b158cfe7690d2fe13a05 to your computer and use it in GitHub Desktop.
Save M-ZubairAhmed/e1dd6587b8c7b158cfe7690d2fe13a05 to your computer and use it in GitHub Desktop.
This Algorithm verifies credit card numbers
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long creditCardNo = 0;
Scanner scan = new Scanner(System.in);
do {
try {
System.out.println("Enter the credit card number you wish to verify");
creditCardNo = scan.nextLong();
} catch (InputMismatchException inMisEx) {
System.out.println("Invalid Credit Card Number, it should be purely digits !");
scan.nextLine();
System.out.println("\n");
}
}
while (creditCardNo <= 0);
StringBuilder cardStr = new StringBuilder();
StringBuilder halfEvenSum = new StringBuilder();
cardStr.append(creditCardNo);
cardStr.reverse();
int sumOdd = 0;
int sumEven = 0;
for (int i = 0; i < cardStr.length(); i++) {
// The odd digits
if (i % 2 == 0) {
int sumOddi = Character.digit(cardStr.charAt(i), 10);
sumOdd = sumOdd + sumOddi;
}
// The even digits
else {
int sumEveni = (Character.digit(cardStr.charAt(i), 10)) * 2;
halfEvenSum.append(sumEveni);
}
}
for (int j = 0; j < halfEvenSum.length(); j++) {
int sumEvenj = Character.digit(halfEvenSum.charAt(j), 10);
sumEven = sumEven + sumEvenj;
}
if ((sumEven + sumOdd) % 10 == 0) {
System.out.print("card number entered is a valid ");
switch (String.valueOf(creditCardNo).substring(0, 2)) {
case "34":
case "37":
System.out.print("American Express Card");
break;
case "51":
case "52":
case "53":
case "54":
case "55":
System.out.print("Master Card");
break;
case "40":
case "41":
case "42":
case "43":
case "44":
case "45":
case "46":
case "47":
case "48":
case "49":
System.out.print("Visa Card");
break;
default:
System.out.print("Card");
break;
}
} else {
System.out.println("Card doesnt match any existing card numbers");
}
}
}
@M-ZubairAhmed
Copy link
Author

Luhn Test

The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the US, Canadian Social Insurance Numbers, and Greek Social Security Numbers (ΑΜΚΑ). It was created by IBM scientist Hans Peter Luhn.
Reference = Wikipedia

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment