第三章第九题(商业:检验ISBN-10)((Business: check ISBN-10))

**3.9(商业:检验ISBN-10)ISBN-10(国际标准书号)由10个个位整数\LARGE d_{1}d_{2}d_{3}d_{4}d_{5}d_{6}d_{7}d_{8}d_{9}d_{10}组成,最后一位\LARGE d_{10}是校验和,它是使用下面的公式用另外9个数计算出来的:

(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9)%11

如果校验和为10,那么按照ISBN-10的习惯,最后一位应该表示为X。编写程序,提示用户输入前9个数,然后显示10位ISBN(包括前面起始位置的0)。程序应该读取一个整数输入。

以下是一个运行示例:
 

Enter the first 9 digits of an ISBN as integer:013601267

The ISBN-10 number is 0136012671

Enter the first 9 digits of an ISBN as integer:013031997

The ISBN-10 number is 013031997X

 
 

**3.9(Business: check ISBN-10) An ISBN-10 (International Standard Book Number) consists of 10 digits: \LARGE d_{1}d_{2}d_{3}d_{4}d_{5}d_{6}d_{7}d_{8}d_{9}d_{10}. The last digit, d10, is a checksum, which is calculated from the other 9 digits using the following formula:

(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9)%11

If the checksum is 10, the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer.

Here are sample runs:

Enter the first 9 digits of an ISBN as integer:013601267

The ISBN-10 number is 0136012671

Enter the first 9 digits of an ISBN as integer:013031997

The ISBN-10 number is 013031997X

 

下面是参考答案代码:

import java.util.Scanner;


public class CheckISBN10Question9 {
	public static void main(String[] args) {
		int isbn,checkSum;
		int d1, d2, d3, d4, d5, d6, d7, d8, d9;
		
		System.out.print("Enter the first 9 digits of an ISBN as integer: ");
		Scanner input = new Scanner(System.in);
		isbn = input.nextInt();
		
		d1 = isbn / 100000000;
		d2 = isbn / 10000000 % 10;
		d3 = isbn / 1000000 % 10;
		d4 = isbn / 100000 % 10;
		d5 = isbn / 10000 % 10;
		d6 = isbn / 1000 % 10;
		d7 = isbn / 100 % 10;
		d8 = isbn / 10 % 10;
		d9 = isbn % 10;
		
		checkSum = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5
				 	+ d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11;

		if(checkSum == 10)
			System.out.println("The ISBN-10 number is "+ d1+d2+d3+d4+d5+d6+d7+d8+d9 + "X");
		else
			System.out.println("The ISBN-10 number is "+ d1+d2+d3+d4+d5+d6+d7+d8+d9 + checkSum);
		
		input.close();
	}
}

运行效果:


注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)

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