这就是作业:
使用 8 位数字检查信用卡号 • 从最右边的数字开始,计算每隔一个数字的总和。例如,如果信用卡号为 4358 9795,则得出的总和为 5 + 7 + 8 + 3 = 23。 • 将上一步中未包含的每个数字加倍。将所得数字的所有数字相加。例如,对于上面给出的数字,从倒数第二个数字开始,将数字加倍,得到 18 18 10 8。将这些值中的所有数字相加,得到 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27。 • 将前面两个步骤的总和相加。如果结果的最后一位为0,则该数字有效。在我们的例子中,23 + 27 = 50,所以这个数字是有效的。 --有效/无效?
我已经创建了一个测试程序和一个单独的方法程序。一切都已成功编译,因此不应该出现任何技术错误,但即使当我输入有效的卡号时,程序也会返回该号码无效,因此我假设实际算法有问题,但我对此很陌生,所以我无法弄清楚它是什么。
import java.util.Scanner;
public class CreditCardTester{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String retry = ("y");
String n = null;
while(retry.equalsIgnoreCase("y")){ // allows program to keep running even if the user enters in a capital Y
int lengthCheck = 1;
System.out.println("Please enter your 8-digit credit card number");
// check to see whether the input number is exactly 8 digits
while(lengthCheck==1){
n = scanner.next();
if(n.length()==8)
lengthCheck=0;
else
System.out.println("Please make sure the credit card number you have entered is 8 digits");
} // end inner while loop
// instantiate CardNumber and check validity
CardNumber number = new CardNumber(n);
number.check();
if (number.isValid())
System.out.println("The number you entered is a valid credit card number.");
else
System.out.println("The number you entered is not a valid credit card number. Would you like to enter in another number? (y/n)");
retry = scanner.next();
} // end outer while loop
}
}
和单独的类
public class CardNumber {
private String number;
private boolean valid;
public CardNumber(String n){
number = n;
valid = true;
}
private void check1(){
int a = Integer.parseInt(number.substring(7));
int b = Integer.parseInt(number.substring(5,6));
int c = Integer.parseInt(number.substring(3,4));
int d = Integer.parseInt(number.substring(1,2));
int oddsum = a + b + c + d;
int e = (Integer.parseInt(number.substring(6,7))) * 2;
int f = (Integer.parseInt(number.substring(4,5))) * 2;
int g = (Integer.parseInt(number.substring(2,3))) * 2;
int h = (Integer.parseInt(number.substring(0,1))) * 2;
String ee = String.valueOf(e);
String ff = String.valueOf(f);
String gg = String.valueOf(g);
String hh = String.valueOf(h);
int evensum = (Integer.parseInt(ee.substring(0))) + (Integer.parseInt(ff.substring(0))) + (Integer.parseInt(gg.substring(0))) + (Integer.parseInt(hh.substring(0)));
int totalsum = evensum + oddsum;
if (!(totalsum%10 == 0))
valid=false;
}
public void check(){
check1();
}
public boolean isValid(){
return valid;
}
}
我确信还有更好的方法来做到这一点,所以所有建议都值得赞赏!
最佳答案
信用卡号验证称为 Luhn 算法。这是一个java实现http://www.xinotes.org/notes/note/595/
对于你的代码,我认为在这里:
int evensum = (Integer.parseInt(ee.substring(0))) + (Integer.parseInt(ff.substring(0))) + (Integer.parseInt(gg.substring(0))) + (Integer.parseInt(hh.substring(0)));
您的意思是对两个数字求和:
int evensum = Integer.parseInt(ee.substring(0,1)) + Integer.parseInt(ee.substring(1)) ...
关于java - 信用卡验证 - 技术上正确但算法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12738098/