ISBN-13 是一个标识书籍的新标准。它使用13位数字d1d2d3d4d5d6d7d8d9d10d11d12d13。最后一位数字d13 是一个校验和,是使用下面的公式从其他数字中计算出来的:
10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12)% 10
*如果校验和为10,将其替换为0。程序应该将输入作为一个字符串输入。
package pack2;
import java.util.Scanner;
public class CheckISBN13 {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the first 12 digits of an ISBN-13 as a string: ");
String isbn = input.nextLine();
try {
System.out.println("The ISBN-13 number is "+checkISBN13(isbn));
} catch (IllegalArgumentException e) { //出现异常时捕获
System.out.println(isbn+" is an invalid input");
}
}
}
//检测ISBN-13
public static String checkISBN13(String isbn) {
//如果字符串长度小于或大于12,抛出异常
if(isbn.length() < 12 || isbn.length() > 12)
throw new IllegalArgumentException();
int sum = 0;
for (int i = 1; i <= isbn.length(); i++) { //处理和
int d = Integer.parseInt(Character.toString(isbn.charAt(i - 1)));
sum += (i % 2 == 0 ? 3 * d : d);
}
sum = 10 - sum % 10;
return isbn+(sum == 10 ? 0 : sum);
}
}