如何实现Luhn算法? [英] How do I implement the Luhn algorithm?

查看:138
本文介绍了如何实现Luhn算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序来验证基于luhn算法的10到12位长数序列,但我的程序一直告诉我每个数字都是无效的,即使它们不是。

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 even though they're not.

此数字应该有效,但我的代码不这么认为: 8112189876

This number should be valid, but my code doesn't think so: 8112189876

此号码无效,我的程序同意,因为它认为每个号码都无效: 8112189875

This number should not be valid, which my program agrees with, as it thinks every number is invalid: 8112189875

这是我的代码:

static void luhn(){
    System.out.print("Enter number to validate:\n");
    String pnr = input.nextLine();
    int length = pnr.length();
    int sum = 0;
    for (int i = 1, pos = length - 1; i < 10; i++, pos--){
        char tmp = pnr.charAt(pos);
        int num = tmp - 0
        int product;
        if (i % 2 != 0){
            product = num * 1;
        }
        else{
            product = num * 2;
        }
        if (product > 9)
            product -= 9;
        sum+= product;              
        boolean valid = (sum % 10 == 0);
        if (valid){
            System.out.print("Valid!\r");
        }
        else{
            System.out.print("Invalid!");
        }
    }
}


推荐答案

我看到的第一件事是你有:

The first thing I see is that you have:

int num = tmp - 0

您应该拥有:

int num = tmp - '0';

其次,您应该验证<$ c之外的 之和$ c> for 循环,因为你只关心处理完所有数字后的总和。

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

第三,你是从结束开始数字,并且您不包括字符串的第一个数字。为什么不对这两个任务使用 i

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?

结果(工作)方法:

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() {

它改为方法签名

static boolean luhn(String input) {

这很容易让你的从任何来源(文件,硬编码等)获取字符串的代码,并对结果执行任何操作(打印消息,或者执行其他操作)。显然你会移动 System.out.print input.nextLine() if(有效)此方法之外的代码位。

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.

完整重构程序:

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!");
    }
  }
}

这篇关于如何实现Luhn算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆