Java中的Luhn信用卡验证

时间:2016-10-11 17:57:39

标签: java

寻求有关我的java程序的帮助,该程序使用Luhn算法验证用户输入的信用卡号。卡号必须在13到16位之间,以4(对于Visa),5(万事达卡),37(美国运通卡)或6(发现)开头。程序应将输入作为长输入,并在输入有效或无效时显示。这是我到目前为止,原谅格式。

即使我输入有效的卡号,打印也是无效的,我不知道为什么。还不确定如何指定卡长度的参数,因为它必须在13-16个字符之间才有效。

import java.util.Scanner;
public class Lunh {

  public static void main(String []args){
      Scanner input = new Scanner(System.in);
      long cardNumber;
      int sum = 0;
     boolean even = false;

      String cardType;
      System.out.println("Enter credit card number"); //prompt user to enter their card number
      cardNumber = input.nextLong();

      String cardNumberString = Long.toString(cardNumber); //card number entered as a long and converted to string 
      isValid(cardNumberString);
  }
    public static boolean isValid(String cardNumber){
    int sum = 0 ;
    boolean even = false;
    String  cardType = null;

    int firstDigit = getDigit(cardNumber,1);
    switch (firstDigit){
        case 4: 
        cardType = "Visa";
        break;
        case 3:
        if (getDigit(cardNumber,2)==7) {
            cardType= "American Express";
            } else {
            return false;
            }
        case 5:
        cardType = "Master Card";
        break;
        case 6: 
        cardType = "Discover";
        break;
    } //end card type switch

    int secondDigit = getDigit(cardNumber, 2);

    //loops through digits in reverse order right to left
    for (int i = cardNumber.length();i>0; i--){
        int digit = getDigit(cardNumber, i);

        //double every other digit
        if (even)
        digit += digit;

        even = ! even;

        //if result is greater than 9 then subtract 9
        if (digit > 9)
        digit = digit - 9;

        sum += digit;
        } //end of loop

    if (sum % 10 == 0) 
    {
        System.out.println(cardNumber+" is valid");
        System.out.println("Card Type: "+cardType);
        return true;
    }
    else {
        System.out.println(cardNumber+ " is invalid");
        System.out.println("Card Type: Invalid");
        return false;
    }
    } //end of isValid class

    //gets digit at specified position
    private static int getDigit(String digitString, int position){
        String characterAtPosition = digitString.substring(position - 1, position);
        return Integer.parseInt(characterAtPosition);
    }  
}

1 个答案:

答案 0 :(得分:1)

你不了解这个算法。另请参阅Luhn_algorithm

输入的最右边数字是校验位。你必须从倒数第二个数字开始你的计算(总和,这看起来基本上是正确的)。然后将总和乘以9模10:

computedCheckDigit = sum*9%10

将此值与输入的最右侧数字进行比较。如果相等则Luhn-Check有效。