|
| 1 | +/** |
| 2 | + * (Business: check ISBN-13) ISBN-13 is a new standard for identifying books. It uses |
| 3 | + * 13 digits d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit d13 is a checksum, which is |
| 4 | + * calculated from the other digits using the following formula: |
| 5 | + * 10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12),10 |
| 6 | + * If the checksum is 10, replace it with 0. Your program should read the input as a |
| 7 | + * string. Here are sample runs: |
| 8 | + * |
| 9 | + * Enter the first 12 digits of an ISBN-13 as a string: 978013213080 |
| 10 | + * The ISBN-13 number is 9780132130806 |
| 11 | + * Enter the first 12 digits of an ISBN-13 as a string: 978013213079 |
| 12 | + * The ISBN-13 number is 9780132130790 |
| 13 | + * Enter the first 12 digits of an ISBN-13 as a string: 97801320 |
| 14 | + * 97801320 is an invalid input |
| 15 | + * |
| 16 | + * Created by Sven on 06/09/19. |
| 17 | + */ |
| 18 | +package Chapter05; |
| 19 | + |
| 20 | +import java.util.Scanner; |
| 21 | + |
| 22 | +public class Exercise0547_Business_check_ISBN_13 { |
| 23 | + public static void main(String[] args) { |
| 24 | + Scanner input = new Scanner(System.in); |
| 25 | + System.out.print("Enter the first 12 digits of an ISBN as integer: "); |
| 26 | + String originalNum = input.next(); |
| 27 | + |
| 28 | + if (originalNum.length() != 12) { |
| 29 | + System.out.println(originalNum + " is an invalid input"); |
| 30 | + } else { |
| 31 | + int sum = 0; |
| 32 | + for (int i = 0; i < originalNum.length(); i++) { |
| 33 | + sum += (i % 2 == 0) ? 3 * (originalNum.charAt(i) - 48) : (originalNum.charAt(i) - 48); |
| 34 | + } |
| 35 | + int checksum = (10 - sum % 10) % 10; // If the checksum is 10, replace it with 0, therefore % 10 |
| 36 | + |
| 37 | + String ISBN13str = originalNum + checksum; |
| 38 | + |
| 39 | + System.out.print("The ISBN-13 number is " + ISBN13str); |
| 40 | + } |
| 41 | + } |
| 42 | +} |
0 commit comments