5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マイナンバーのチェックデジットを計算する(Java編)

Posted at

マイナンバーのチェックデジットを計算する(http://qiita.com/qube81/items/fa6ef94d3c8615b0ce64) を読んでJavaで実装してみました。
SIer脳で書いたJavaコードなので、もっときれいな書き方が絶対あるはず。

import org.apache.commons.lang3.math.NumberUtils;

/**
 * マイナンバーのチェックディジットを求める。
 */
public class CheckDigit {

    public static int calcCheckDigit(String mynumber) {

        // オードソックスな引数チェック
        if (mynumber == null) {
            throw new IllegalArgumentException("引数にnullは指定不可");
        }

        if (mynumber.length() != 11) {
            throw new IllegalArgumentException("引数は11桁必須");
        }

        if (!NumberUtils.isNumber(mynumber)) {
            throw new IllegalArgumentException("引数は数値必須");
        }

        char[] mynumberArgs = mynumber.toCharArray();
        int[] calcResultArgs = new int[11];
        for (int i = 0; i < mynumberArgs.length; i++) {
            calcResultArgs[i] = calc(mynumberArgs[(11 - 1) - i], (i + 1));
        }

        // n=1からn=11までのPn,Qn,Pn×Qnを計算
        int calcTotal = 0;
        for (int val : calcResultArgs) {
            calcTotal += val;
        }

        // 求めた和を11で割ったあまりを求める。
        int amari = calcTotal % 11;

        // 11-(11で割ったあまり)がチェックディジット
        int digit = 11 - amari;

        return digit;

    }

    private static int calc(char c, int n) {

        int i = Character.getNumericValue(c);

        if (n >= 1 && n < 7) {
            return i * (n + 1);
        } else {
            return i * (n - 5);
        }

    }

}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author deaf.tadashi
 */
public class Main {

    private static final Logger log = LoggerFactory.getLogger(Main.class);
    
    public static void main(String[] args) {

        int digit = CheckDigit.calcCheckDigit("12345678901");
        log.info("{}のチェックディジットは{}です。", "12345678901", digit);

    }

}
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?