第三章第九题(商业:检验ISBN-10)((Business: check ISBN-10))
-
**3.9(商业:检验ISBN-10)ISBN-10(国际标准书号)由10个个位整数d1d2d3d4d5d6d7d8d9d10组成,最后一位d10是校验和,它是使用下面的公式用另外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: d1d2d3d4d5d6d7d8d9d10. 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
-
参考代码:
package chapter03;
public class Code_09 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the first 9 digits of an ISBN as integer: ");
int first9Digits = input.nextInt();
int d9 = first9Digits %10;
int d8 = first9Digits /10 % 10;
int d7 = first9Digits /100 % 10;
int d6 = first9Digits /1000 % 10;
int d5 = first9Digits /10000 % 10;
int d4 = first9Digits /100000 % 10;
int d3 = first9Digits /1000000 % 10;
int d2 = first9Digits /10000000 % 10;
int d1 = first9Digits /100000000;
int d10 = (int)((d1 *1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9)%11);
if(d10 == 10)
System.out.println("The ISBN-10 number is " +first9Digits+"X");
else
System.out.println("The ISBN-10 number is " +first9Digits+d10);
}
}
- 结果显示:
Enter the first 9 digits of an ISBN as integer: 013601267
The ISBN-10 number is 136012671
Process finished with exit code 0