第五章第四十七题(商业:检测ISBN-13)(Business: check ISBN-13)

*5.47(商业:检测ISBN-13)ISBN-13是标识书籍的新标准。它使用13位数字d1d2d3d4d5d6d7d8d9d10d11d12d13。最后一位数字d13是校验和,是使用下面的公式从其他数字中计算出来的:

10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12) % 10

如果校验码是10,将其替换为0。程序应该将输入作为一个字符读入。

下面是一个运行示例:

Enter the first 12 digits of an ISBN-13 as a string:  978013213080

The ISBN-13 number is 9780132130806

Enter the first 12 digits of an ISBN-13 as a string:  978013213079

The ISBN-13 number is 9780132130790

Enter the first 12 digits of an ISBN-13 as a string:  97801320

97801320 is an invalid input

 

*5.47(Business: check ISBN-13) ISBN-13 is a new standard for identifying books. It uses 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit d13 is a checksum, which is calculated from the other digits using the following formula:

10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12) % 10

If the checksum is 10, replace it with 0. Your program should read the input as a string.

 
Here are sample runs:
 

Enter the first 12 digits of an ISBN-13 as a string:  978013213080

The ISBN-13 number is 9780132130806

Enter the first 12 digits of an ISBN-13 as a string:  978013213079

The ISBN-13 number is 9780132130790

Enter the first 12 digits of an ISBN-13 as a string:  97801320

97801320 is an invalid input

 

下面是参考答案代码:

import java.util.*;


public class  CheckISBN13Question47 {
	public static void main(String[] args) {
		String isbnString;
		int checksum = 0,d13;
		
		Scanner inputScanner = new Scanner(System.in);
		System.out.print("Enter the first 12 digits of an ISBN-13 as a string: ");
		isbnString = inputScanner.nextLine();
		if(isbnString.length() != 12)
		{
			System.out.printf("%s is an invalid input", isbnString);
			System.exit(1);
		}
		
		for(int i = 0;i < 12;i++)
		{
			if(i % 2 == 1)
				checksum += 3 * Integer.parseInt(String.valueOf(isbnString.charAt(i)));
			else
				checksum += Integer.parseInt(String.valueOf(isbnString.charAt(i)));
		}
		d13 = 10 - checksum % 10;
		if(d13 == 10)
			d13 = 0;
		
		System.out.printf("The ISBN-13 number is %s%d", isbnString, d13);
		
		inputScanner.close();
	}
}

运行效果:

 

注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等

你可能感兴趣的:(#,第五章课后习题答案)