我正在尝试创建一种方法来验证信用卡号,但我们必须将其作为字符串处理
这里有一些关于我的任务的信息......
信用卡号码遵循某些模式。信用卡必须有 13 到 16 位数字。
1954 年,IBM 的 Hans Luhn 提出了一种验证信用卡号码的算法。该算法可用于确定卡号是否正确输入或信用卡是否被扫描仪正确扫描。几乎所有的信用卡号码都是在这个有效性检查之后生成的,通常称为 Luhn 检查或 Modulus 10 检查,可描述如下。为了说明,请考虑卡号 4388576018402625。
从右到左每隔一个数字加倍。如果一个数字加倍得到一个 2 位数的数字,则将这两个数字相加得到一个个位数的数字。2 x 2 = 4
2 x 2 = 4
4 x 2 = 8
1 x 2 = 2
6 x 2 = 12 (1+2= 3)
5 x 2 = 10 (1+0= 1)
8 x 2 = 16 (1+6= 7)
4 x 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
如果 step 的结果能被 10 整除,则卡号有效;否则无效。例如号码4388576018402625无效,但号码4388576018410707是有效的Visa卡;号码 6011000593748745 无效,但号码 6011000593748746 是有效的 Discover 卡。
这是我到目前为止所拥有的
static void CreditCardValidator() {
System.out.println("enter a credit card number");
String temp = options.nextLine();
if (temp.length() < 13 || temp.length() > 16) {
System.out.println("Input is invalid");
}
// inside loop with char at command do all the math
int tmpdouble;
int sum = 0;
int counter = temp.length() - 1;
for (int i = temp.length(); i != 0; i--) {
char tmp = temp.charAt(i);
//tmp converted to int
tmpdouble = tmp * 2;
int firstDigit;
int secondDigit;
if (tmpdouble >= 10) {
firstDigit = i / 10;
secondDigit = i % 10;
sum = sum + firstDigit + secondDigit;
}
else if(tmpdouble <= 9) {
sum = sum + tmpdouble;
}
HELP HERE{
// need to have it do the same thing as above but for odd numbers
}
我从那里去哪里?^^
谢谢