我正在研究信用卡号验证应用程序。
我可以输入有效数字或无效数字,但是输出从不接受数据并将其读取为有效数据。我正在尝试找出正确的信用卡验证算法。
下面是我想要的结果。我需要知道循环的哪一点,或者我弄乱了long vs. string的用法,这会导致输出始终显示为无效。
示例1:
Enter a credit card number: 4246345689049834
4246345689049834 is invalid
示例2:
Enter a credit card number: 4388576018410707
4388576018410707 is valid
但是,在我的代码中,我得到了以下输出
示例1:
Enter a credit card number: 4246345689049834
4246345689049834 is invalid
示例2:
Enter a credit card number: 4388576018410707
4388576018410707 is invalid
代码:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Credit Card Number for Validation: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + sumOfOddPlaces(number);
if (isValid(total)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long total) {
if (total % 10 == 0) {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
number %= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder);
number /= 100;
}
return sum;
}
}
答案 0 :(得分:1)
您在sumOfEvenPlaces()
和sumOfOddPlaces()
方法中都犯了错误。
在sumOfEvenPlaces(long number)
中,您必须进行更改
number %= 10;
到
number /= 10;
您只能使用数字/ 10跳过数字,而不能跳过数字%10
在两个函数中都更改
while (number % 10 != 0 || number / 10 != 0)
到
while (number > 0)
使用while(数字> 0)循环将一直运行,直到处理完数字中的所有数字为止。
尝试这些修改后的方法,它将起作用:-
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
number /= 10; // change 1
while (number > 0) { // change 2
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
while (number > 0) { // change 3
remainder = (int) (number % 10);
sum = sum + getDigit(remainder);
number /= 100;
}
return sum;
}
输出:-
Enter Credit Card Number for Validation:
4246345689049834
4246345689049834 is invalid