## Java Program - Credit Card Numbers Patterns

• 5th Jun, 2019
• 17:09 PM

Question

Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits. It must start with:

• 4 for Visa cards
• 5 for Master cards
• 37 for American Express cards
• 6 for Discover cards

In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine if a card number is entered correctly or if a credit card is scanned correctly by a scanner. Almost all credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number

```
{

public static void main(String[] args) {
// TODO Auto-generated method stub
if (args.length != 1) {
System.out.println("Invalid argument.");
return;
}
if (args[0].length() < 13 || args[0].length() > 16) {
System.out.println("The number " + args[0] + "is invalid");
return;
}
boolean startValid = false;
String cardNumber = args[0];

if (cardNumber.charAt(0) == '4' || cardNumber.charAt(0) == '5' || cardNumber.charAt(0) == '6')
startValid = true;
if(cardNumber.charAt(0) == '3' && cardNumber.charAt(1) == '7')
startValid = true;
int doubleResult = 0;
int singleResult = 0;
int count = 0;
for(int i = cardNumber.length() - 1; i >= 0; --i, ++count)
{
if(count % 2 == 0)
{
singleResult += Character.getNumericValue(cardNumber.charAt(i));
}
else
{
int temp = Character.getNumericValue(cardNumber.charAt(i));
temp *= 2;
if(temp >= 10)
{
adding = (int)(temp / 10) + (int)(temp % 10);
}
else
}
}
//System.out.println("DEBUG: double result:" + doubleResult);
//System.out.println("DEBUG: single result:" + singleResult);

if(startValid == true && (singleResult + doubleResult) % 10 == 0)
{
System.out.println("The number " + args[0] + " is valid");
}
else
{
System.out.println("The number " + args[0] + " is invalid");
}

}

}
```