All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.model.Card Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
package shz.core.model;

import shz.core.NullHelp;
import shz.core.msg.ClientFailureMsg;

import java.util.regex.Pattern;

public class Card {
    private static final Pattern P_LUNE_CHECK = Pattern.compile("^\\d{8,19}$");
    private static final Pattern P_LUNE_COMPUTE = Pattern.compile("^\\d{7,18}$");
    private String no;

    public Card() {
    }

    public Card(String s) {
        ClientFailureMsg.requireNon(!check(s), "不是一个合法的卡号");
        no = s;
    }

    @Override
    public String toString() {
        return "Card{" +
                "no='" + no + '\'' +
                '}';
    }

    public static boolean check(String s) {
        if (s == null || !P_LUNE_CHECK.matcher(s).matches()) return false;
        return compute(s.substring(0, s.length() - 1)) == s.charAt(s.length() - 1) - '0';
    }

    public static int compute(String s) {
        int len;
        if ((len = NullHelp.length(s)) == 0 || !P_LUNE_COMPUTE.matcher(s).matches()) return -1;

        int sum = 0;
        for (int i = len - 1, j = 0; i > -1; --i, ++j) {
            int n = s.charAt(i) - '0';
            if ((j & 1) == 0) {
                n <<= 1;
                n = n / 10 + n % 10;
            }
            sum += n;
        }

        int mod = sum % 10;
        return mod == 0 ? 0 : 10 - mod;
    }

    public final boolean create() {
        int compute = compute(no);
        if (compute == -1) return false;
        char[] chars = new char[no.length() + 1];
        no.getChars(0, no.length(), chars, 0);
        chars[no.length()] = (char) ('0' + compute);
        no = new String(chars);
        return true;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy