gpt4 book ai didi

java - 在 Java 中验证 CCN?

转载 作者:行者123 更新时间:2023-11-29 03:05:51 26 4
gpt4 key购买 nike

我正在尝试编写信用卡验证程序。然而,我终究无法弄清楚为什么我输入的完全有效的信用卡会变得无效。

我正在使用 Luhn 方程进行验证。

Luhn方法如下:

卢恩公式:

  • 去掉数字的最后一位。最后一位就是我们想要的对照
  • 反转数字。
  • 将奇数位(1、3、5 等)的数字乘以 2,然后将所有大于 9 的结果减去 9。
  • 将所有数字加在一起 ​​校验位(最后一个数字卡)是您需要添加的金额才能获得
    10 的倍数(模 10)

信用卡示例来自 this website, where I also got the equation from.

我的密码是here, on Gist.

谢谢!

(此外,这是我第一次使用 Javadoc!让我知道我是怎么做到的!)

编辑:我正在使用的 Luhn 方法显然不起作用:

/**
* Runs the Luhn Equation on a user inputed CCN, which in turn
* determines if it is a valid card number.
* @param c A user inputed CCN.
* @param cn The check number for the card.
* @return If the card is valid based on the Luhn Equation.
*/
public boolean luhn (String c, char cn)
{
String card = c;

//Drop the last digit.
card = card.substring(0, ( card.length() - 1 ) );

//Reverse the digits.
String cardrev = new StringBuilder(card).reverse().toString();

//Store it in an int array.
char[] cardArray = cardrev.toCharArray();
int[] cardWorking = new int[cardArray.length];
int addedNumbers = 0;

for (int i = 0; i < cardArray.length; i++)
{
cardWorking[i] = Character.getNumericValue( cardArray[i] );
}

//Double odd digits (which are really even in our case, since index starts at 0).

for (int j = 0; j < cardWorking.length; j++)
{
if ( j % 2) == 0)
{
cardWorking[j] = cardWorking[j] * 2;
}
}

//Subtract 9 from digits larger than 9.

for (int k = 0; k < cardWorking.length; k++)
{
if (cardWorking[k] > 9)
{
cardWorking[k] = cardWorking[k] - 9;
}
}

//Add all the numbers together.
for (int l = 0; l < cardWorking.length; l++)
{
addedNumbers += cardWorking[l];
}

//Finally, check if the number we got from adding all the other numbers
//when divided by ten has a remainder equal to the check number.
if (addedNumbers % 10 == cn)
{
return true;
}
else
{
return false;
}
}

编辑 2:

我认为问题出在这里,但我不确定为什么。 addedNumbers 为 50,cn 为 0,但仍然返回 false。

if (addedNumbers % 10 == cn)
{
//Debug
System.out.println(addedNumbers + " % 10 = " + cn);

return true;
}
else
{
//Debug
System.out.println(addedNumbers + " % 10 =/= " + cn);

return false;
}

我在控制台的输出:

>4024007142327070
707232417004204
[7, 0, 7, 2, 3, 2, 4, 1, 7, 0, 0, 4, 2, 0, 4]
[14, 0, 14, 2, 6, 2, 8, 1, 14, 0, 0, 4, 4, 0, 8]
[5, 0, 5, 2, 6, 2, 8, 1, 5, 0, 0, 4, 4, 0, 8]
50
50 % 10 =/= 0

You inputted card: 4024007142327070
Your card is not valid because it doesn't check against the Luhn Equation.

50 % 10 =/= 0

那是不对的。这是怎么回事?

快速编辑。

我很生气,我检查了。

50 modulo 10 is in fact, 0.

50 模 10 实际上是 0。

最佳答案

使用 apache commons-validator 中的 org.apache.commons.validator.CreditCardValidator。

关于java - 在 Java 中验证 CCN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com