信用卡号码符合特定模式。信用卡必须有13到16位数字。它必须先从:
•4 Visa卡
•5主卡
•37美国运通卡
在1954年,IBM的汉斯·卢恩提出的算法验证信用卡号。该算法对于确定卡号是否正确输入或扫描仪是否正确扫描信用卡很有用。几乎所有的信用卡号码都是在此有效性检查后生成的,通常称为Luhn支票或Modulus 10支票,可以描述如下。为了说明,请考虑卡号4388576018402625.
从右到左每隔两位数字双击一次。如果一个数字加倍会得到一个2位数的数字,请将这两个数字相加得到一位数字。
2×2 = 4
2×2 = 4
4×2 = 8
1×2 = 2
6×2 = 12(1+ 2 = 3)
5×2 = 10(1 + 0 = 1)
8×2 = 16(1 + 6 = 7)
4×2 = 8
从步骤1 4 + 4 8 + 2 3 + 1 + 7 + 8 = 37添加所有的个位数
在奇数地方添加所有数字从右卡号到左
5 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 37
萨姆从步骤2和步骤3的结果 37 + 37 = 74
如果来自步骤的结果是被10整除,卡号码是有效的;否则,它是无效的。例如,号码4388576018402625无效,但号码4388576018410707是有效的Visa卡;号码6011000593748745无效,但号码6011000593748746是有效的发现卡。
我试图解决它,如下面的代码:
import java.util.Scanner;
public class CreditCardValidation {
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=13) && (getSize(number)<=16)) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number/10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number/100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp/10) * 2);
number = number/100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d/10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number/10;
}
return number;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long input = sc.nextLong();
if (isValid(input) == true) {
System.out.println("\n" + input + " is Valid. ");
} else {
System.out.println("\n" + input + " is Invalid. ");
}
}
}
我的问题是如何使用数组来存储,而不是使用长数的信用卡号码。
+2
你可以使用'String' ... –
+0
我已经给了一个答案到今天看起来相同问题的第二篇文章 - 请参阅[链接](http://stackoverflow.com/questions/20740444/check-credit-card-validity-using-luhn-algorithm)。 –