java组织机构代码_JAVA实现社会统⼀信⽤代码校验的⽅法⽹上了⼏个,写的都不太适合,有的写出来了,也没有给出参考的算法链接。这样就导致了如果产⽣错误我们⽆法排查(不懂原理怎么排查对吧)。
如果在使⽤过程中有疑虑,请参考:较验规则
unzhimon.utils;
import llections4.BidiMap;
import llections4.bidimap.TreeBidiMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.ValidationException;
import java.util.Map;
import java.util.Random;
/**
* 统⼀社会停⽤⽤代码
*/
public interface UnifiedCreditCodeUtils {
Logger logger = Logger(UnifiedCreditCodeUtils.class);
String baseCode = "0123456789ABCDEFGHJKLMNPQRTUWXY";
char[] baseCodeArray = CharArray();
int[] wi = {1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28};
/**
* ⽣成供较验使⽤的 Code Map
*
* @return BidiMap
*/
static BidiMap generateCodes() {
BidiMap codes = new TreeBidiMap<>();
nextint()方法for (int i = 0; i < baseCode.length(); i++) {
codes.put(baseCodeArray[i], i);
}
return codes;
}
/**
* 较验社会统⼀信⽤代码
*
* @param unifiedCreditCode 统⼀社会信息代码
* @return 符合: true
*/
static boolean validateUnifiedCreditCode(String unifiedCreditCode) {
if ((unifiedCreditCode.equals("")) || unifiedCreditCode.length() != 18) {
return false;
}
Map codes = generateCodes();
int parityBit;
try {
parityBit = getParityBit(unifiedCreditCode, codes);
} catch (ValidationException e) {
return false;
}
return parityBit == (unifiedCreditCode.charAt(unifiedCreditCode.length() - 1)); }
/**
* 获取较验码
*
* @param unifiedCreditCode 统⼀社会信息代码
* @param codes 带有映射关系的国家代码
* @return 获取较验位的值
*/
static int getParityBit(String unifiedCreditCode, Map codes) {
char[] businessCodeArray = CharArray();
int sum = 0;
for (int i = 0; i < 17; i++) {
char key = businessCodeArray[i];
if (baseCode.indexOf(key) == -1) {
throw new ValidationException("第" + String.valueOf(i + 1) + "位传⼊了⾮法的字符" + key); }
sum += ((key) * wi[i]);
}
int result = 31 - sum % 31;
return result == 31 ? 0 : result;
}
/**
* 获取⼀个随机的统⼀社会信⽤代码
*
* @return 统⼀社会信⽤代码
*/
static String generateOneUnifiedCreditCode() { Random random = new Random();
StringBuilder buf = new StringBuilder();
for (int i = 0; i < 17; ++i) {
int num = Int(baseCode.length() - 1); buf.append(baseCode.charAt(num));
}
String code = String();
String upperCode = UpperCase();
BidiMap codes = generateCodes();
int parityBit = getParityBit(upperCode, codes);
if (Key(parityBit) == null) {
logger.debug("⽣成社会统⼀信⽤代码不符合规则"); upperCode = generateOneUnifiedCreditCode();
} else {
upperCode = upperCode + Key(parityBit); }
return upperCode;
}
}
测试
unzhimon.utils;
import api.Assertions;
import org.junit.Test;
import static org.junit.Assert.*;
public class UnifiedCreditCodeUtilsTest {
@Test
public void validateUnifiedCreditCode() {
String code = "911310827965850580";
Assertions.assertThat(UnifiedCreditCodeUtils.validateUnifiedCreditCode(code)).isTrue(); }
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。