我在Java类的简介中,我在编写信用卡验证程序的校验和算法时遇到了麻烦。要求是:
还指出我们需要使用循环来完成此操作。我知道我可能需要一个for循环,但我只是坚持如何完成它。这就是我所拥有的:
public static boolean isValidNumber(String cardNumber) {
//your code here
int i, checkSum = 0;
// Compute checksum of every other digit starting from right-most digit
for (i = cardNumber.Length - 1; i >= 0; i -= 2) {
checkSum += (cardNumber[i] - '0');
}
// Now take digits not included in first checksum, multiple by two,
// and compute checksum of resulting digits
for (i = cardNumber.Length - 2; i >= 0; i -= 2) {
int val = ((cardNumber[i] - '0') * 2);
while (val > 0) {
checkSum += (val % 10);
val /= 10;
}
}
// Number is valid if sum of both checksums MOD 10 equals 0
return ((checkSum % 10) == 0);
}
我在两个for循环中都遇到错误。 有什么帮助吗?
答案 0 :(得分:0)
要从给定索引处的字符串中获取char,请使用string.charAt(index)
public static boolean isValidNumber(String cardNumber) {
//your code here
int i, checkSum = 0;
//To find the length of the string use string.length() not string.Length
for (i = cardNumber.length() - 1; i >= 0; i -= 2) {
//to get char from a string at a given position use string.charAt(index)
checkSum += (cardNumber.charAt(i) - '0');
}
for (i = cardNumber.length() - 2; i >= 0; i -= 2) {
int val = ((cardNumber.charAt(i) - '0') * 2);
while (val > 0) {
checkSum += (val % 10);
val /= 10;
}
}
// Number is valid if sum of both checksums MOD 10 equals 0
return ((checkSum % 10) == 0);
}