我正在使用for语句和字符串实现Luhn算法。
我的问题是,"j"是在字符串的那个位置(数字)分配字符的值,还是在字符串长度中分配其数字位置的值?
谢谢
*如果我不应该将代码直接粘贴到其中,请道歉
*编辑:我很确定它实际上并没有检索字符,而只是它在字符串中的数字位置,研究字符方法
if (card.length() < 13 || card.length() > 16)
{
JOptionPane.showMessageDialog(null, "Invalid credit card number");
card = JOptionPane.showInputDialog("Please enter the credit card number.");
num = Long.parseLong(card);
}
for (int j = 0; j < card.length(); j++) {
sum = sum + j*2;
if ( j%2 != 0 ) {
product = j * 1;
sum += product;
}
else {
product = j * 2;
}
if (product > 9) {
product -= 9;
sum += product;
}
}
你有一个for
语句
for (int j = 0; j < card.length(); j++) {
它声明并初始化值为 0 的变量j
。它使用 j++
表达式在每次迭代时将 j
的值递增 1。当j
的值小于 card.length()
的值时,它会执行此操作。
位置的编号。 card.length()
返回一个 int,因此j
将获得该值("位置")。
请尝试以下示例以查看差异:
String s = "Hello World";
for (int i = 0; i < s.length(); i++){
System.out.println(" Value of i: " + i);
System.out.println(" Value of i in s: " + s.charAt(i));
System.out.println("Value of i as char: " + (char)i);
System.out.println("---");
}
前 3 次迭代:
Value of i: 0
Value of i in s: H
Value of i as char: NUL**
---
Value of i: 1
Value of i in s: e
Value of i as char: SOH**
---
Value of i: 2
Value of i in s: l
Value of i as char: STX**
** 字符值不可见,您可以在此处查找:http://ascii.cl/如果i
达到 33 - 它将变得可读,从 !
开始。
在你的代码中,"j"只是位置,将得到值:0,1,2,3,4...,直至字符串长度。
你想要的是该位置的字符所代表的数字,因此字符"0"(具有值 x"30")需要转换为值为 +0 的整数,字符"9"(x'39')需要转换为整数值 +9。
您可以执行以下任一操作:
int cval = Integer.parseInt(card.charAt(j));
或者快速而肮脏:
int cval = card.charAt(j) - 30;
当你给它一个非数字字符时,第一种方法会抛出一个异常,第二个方法将从它得到的任何内容中减去 30(哪个代码是一个非常高值的 unicode 字符),所以只有在你完全确定字符串将只包含 ASCII 字符时才使用此方法0123456789。