How do I implement the Luhn algorithm?

后端 未结 8 1602
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 09:50

I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid

相关标签:
8条回答
  • 2020-12-21 10:25
    package randomNumGen;
    
    public class JavaLuhnAlgorithm {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
    
    
    
            validateCreditCardNumber("8112189876");
            String imei = "012850003580200";
            validateCreditCardNumber(imei);
        }
    
        private static void validateCreditCardNumber(String str) {
    
            int[] ints = new int[str.length()];
            for (int i = 0; i < str.length(); i++) {
                ints[i] = Integer.parseInt(str.substring(i, i + 1));
            }
            for (int i = ints.length - 2; i >= 0; i = i - 2) {
                int j = ints[i];
                j = j * 2;
                if (j > 9) {
                    j = j % 10 + 1;
                }
                ints[i] = j;
            }
            int sum = 0;
            for (int i = 0; i < ints.length; i++) {
                sum += ints[i];
            }
            if (sum % 10 == 0) {
                System.out.println(str + " is a valid credit card number");
            } else {
                System.out.println(str + " is an invalid credit card number");
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-21 10:26

    The first thing I see is that you have:

    int num = tmp - 0
    

    You should instead have:

    int num = tmp - '0';
    

    Secondly, you should be validating your sum outside of the for loop, because you only care about the sum after processing all the digits.

    Thirdly, you are starting from the end of the number, and you are not including the first number of your string. Why not use i for both tasks?

    Resulting (working) method:

    static void luhn(){
      System.out.print("Enter number to validate:\n");
      String pnr = input.nextLine();
      // this only works if you are certain all input will be at least 10 characters
      int extraChars = pnr.length() - 10;
      if (extraChars < 0) {
        throw new IllegalArgumentException("Number length must be at least 10 characters!");
      }
      pnr = pnr.substring(extraChars, 10 + extraChars);
      int sum = 0;
      // #3: removed pos
      for (int i = 0; i < pnr.length(); i++){
        char tmp = pnr.charAt(i);
        // #1: fixed the '0' problem
        int num = tmp - '0';
        int product;
        if (i % 2 != 0){
          product = num * 1;
        }
        else{
          product = num * 2;
        }
        if (product > 9)
          product -= 9;
        sum+= product;              
      }
      // #2: moved check outside for loop
      boolean valid = (sum % 10 == 0);
      if (valid){
        System.out.print("Valid!\r");
      }
      else{
        System.out.print("Invalid!");
      }
    }
    

    Stylistically, this method would be more useful if, instead of method signature

    static void luhn() {
    

    it instead had method signature

    static boolean luhn(String input) {
    

    This easily allows your code to get the String from ANY source (a file, hardcoded, etc.) and do anything with the result (print a message as yours does, or do something else). Obviously you would move the System.out.print, input.nextLine(), and if(valid) bits of code outside of this method.

    Full refactored program:

    import java.util.Scanner;
    
    public class Luhn {
      private static Scanner input;
    
      public static void main(String... args) {
        input = new Scanner(System.in);
        System.out.print("Enter number to validate:\n");
        String pnr = input.nextLine();
        boolean result = luhn(pnr);
        printMessage(result);
        input.close();
      }
    
      static boolean luhn(String pnr){
        // this only works if you are certain all input will be at least 10 characters
        int extraChars = pnr.length() - 10;
        if (extraChars < 0) {
          throw new IllegalArgumentException("Number length must be at least 10 characters!");
        }
        pnr = pnr.substring(extraChars, 10 + extraChars);
        int sum = 0;
        for (int i = 0; i < pnr.length(); i++){
          char tmp = pnr.charAt(i);
          int num = tmp - '0';
          int product;
          if (i % 2 != 0){
            product = num * 1;
          }
          else{
            product = num * 2;
          }
          if (product > 9)
            product -= 9;
          sum+= product;              
        }
        return (sum % 10 == 0);
      }
    
      private static void printMessage(boolean valid) {
        if (valid){
          System.out.print("Valid!\r");
        }
        else{
          System.out.print("Invalid!");
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题