public static void main(String[] args) {
/*
* 生成13位条形码 Ean-13码规则: 第十三位数字是前十二位数字经过计算得到的校验码。 例如:690123456789
* 计算其校验码的过程为:
*
* @前十二位的奇数位和6+0+2+4+6+8=26
*
* @前十二位的偶数位和9+1+3+5+7+9=34
*
* @将奇数和与偶数和的三倍相加26+34*3=128
*
* @取结果的个位数:128的个位数为8
*
* @用10减去这个个位数10-8=2 所以校验码为2
* (注:如果取结果的个位数为0,那么校验码不是为10(10-0=10),而是0)
* 实现方法ean13()计算验证码,输入12位条码,返回带验证码的条码。
* 例:输入:692223361219输出:6922233612192
*/
System.out.println(ean13());
}
public static String ean13() {
String str;
int sum = 0;
int jiSum = 0;
int ouSum = 0;
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("请输入十二位条形码:");
str = sc.next();
if(str.length()==12){
break;
}else{
System.out.println("字符串长度不正确,请重新输入!");
}
}
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
int ch = str.charAt(i)-'0';
jiSum += ch;
} else {
int ch = str.charAt(i)-'0';
ouSum += ch;
}
}
sum=jiSum+ouSum*3;
int gewei = sum%10;
if(gewei==0){
return str+gewei;
}
return str+(10-gewei);
}
04-22
7287
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-26
9446
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)