Question
I need help with this question: Chapter 3 question 9: An ISBN-10 consists of 10 digits: d1, d2, d3, d4, d5, d6, d7, d8, d9, d10. The last digit, d10, is a checksum, which is calculated from theother nine digits using the following formula: (d1*1 + d2 *2 + d3*3 + d4*4 + d5*5 + d6*6 + d7*7 + d8*8 + d9*9) 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.
Explanation / Answer
(1) Stick with strings here. If you try to pad an integer type it will be processed as an octal. E.g. int n = 010 n += 1; System.out.println(n); //displays 9, not 11 (2) StringBuilder is a more efficient way of working with strings. Since you have to insert 0's to pad it, you may use String.concat(). But, since strings are immutable (can't be changed), a simple statement like the one below will generate 3 strings in memory. All literals are created at compile time in read-only memory, so they're immutable. String s = "hello"; s = s.concat(" world"); "hello" is a string in memory, "world" is a string in memory", and "hello world" is a string in memory. That's very space inefficient. StringBuilder takes care of this. (4) Since we're using strings you have to convert each character to it's proper numerical equivalent using the ascii encodings. This is important for the checksum computation. E.g. char c = '9'; int n = c; System.out.print(n); //displays 57 n = (int)c - 48; System.out.print(n); //displays 9 That's pretty much it. ///////////////// import java.util.Scanner; public class ComputeISBN { private String isbn; public ComputeISBN(int n) { String s = pad(n); isbn = computeISBN(s); } /** * Apply a zero pad to the front of a number, so that its length is 9. * @param n A number. * @return The padded number. */ private String pad(int n) { StringBuilder sb = new StringBuilder(n+""); int padCount = 9 - sb.length(); for(int i = 0; i