如何为Luhn算法程序编写自定义函数来确定卡是Amex, Mastercard还是Visa



我正在编写一个验证信用卡的Java程序。该程序可以提示用户输入CC号。它成功地检查输入的数字是否有效。但是我不明白如何为程序添加用户定义的函数来确定CC号是American Express, MasterCard还是Visa卡号,因为所有这些卡都有不同的格式。

电流输出:

Hello! This is a Credit Card validation program.

Please enter your credit card number : (user input : 378282246310005 - valid cc number)
Your credit card number is true

期望输出:

Hello! This is a Credit Card validation program.

Please enter your credit card number : (user input : 378282246310005 - valid cc number)
Your credit card number is true and is an American Express CC Number(or Visa/Mastercard, depending on user's input)

代码:https://pastebin.com/bHSsSCPV

public static void main(String[] args) {

//concatenating the isValid variable into output (string concatonation)
System.out.println("Hello! This is a Credit Card validation program.");
System.out.println("                                                ");
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your credit card number : ");
String creditCardNumber = sc.nextLine();
boolean isValid = validateCreditCardNumber(creditCardNumber);
System.out.println("                                                ");
System.out.println("Your credit card number is " +isValid);
}
private static boolean validateCreditCardNumber(String input) 
{    
//Input conversion to int
int[] creditCardInt = new int [input.length()];


//doubling each other digit starting from the right, if > than 9, mod 10 and + 1 to the remainder
for (int i = 0; i <input.length(); i++ )
{
creditCardInt[i] = Integer.parseInt(input.substring (i, i + 1));
}

for (int i = creditCardInt.length - 2; i >= 0; i = i - 2)
{
int tempValue = creditCardInt[i];
tempValue = tempValue * 2;
if (tempValue > 9)
{
tempValue = tempValue % 10 + 1;
}
creditCardInt[i] = tempValue; 
}
//+ all the digits
int total = 0;
for (int i = 0; i < creditCardInt.length; i++)
{
total += creditCardInt [i];
}

//If number is a multiple of 10, it is valid..else it is invalid
if (total % 10 == 0)
{
return true;
}
else
{
return false;
}   
}   
}

credit card number format上简单地搜索一下就得到了这个。

Visa卡-以4开头,有13或16位数字。万事达卡-以5开头,有16位数字。美国运通卡-以3开头,后面跟着4或7,有15位数字. ...大来卡和全权委托卡——以数字3开头,后面跟着数字0、6或8,共有14位数字。

我建议你继续在网上搜索适当的格式分解以及验证过程(所有的卡可能不会以相同的方式验证),包括应用CCV或等效值。然后,只需调用适当的方法来验证该卡。请注意,有些卡片可能有一些共同的过程,这意味着它们可以共享另一种方法。

最新更新