Answer:
Here is the JAVA program:
import java.util.Scanner; //to import Scanner class
public class ISBN
{ public static void main(String[] args) { // start of main() function body
Scanner s = new Scanner(System.in); // creates Scanner object
//prompts the user to enter 10 digit integer
System.out.println("Enter the digits of an ISBN as integer: ");
String number = s.next(); // reads the number from the user
int sum = 0; // stores the sum of the digits
for (int i = 2; i <= number.length(); i++) {
//loop starts and continues till the end of the number is reached by i
sum += (i * number.charAt(i - 1) ); }
/*this statement multiplies each digit of the number with i and adds the value of sum to the product result and stores in the sum variable*/
int remainder = (sum % 11); // take mod of sum by 11 to get checksum
if (remainder == 10)
/*if remainder is equal to 10 adds X at the end of given isbn number as checksum value */
{ System.out.println("The ISBN number is " + number + "X"); }
else
// displays input number with the checksum value computed
{System.out.println("The ISBN number is " + number + remainder); } } }
Explanation:
This program takes a 10-digit integer as a command line argument and uses Scanner class to accept input from the user.
The for loop has a variable i that starts from 2 and the loop terminates when the value of i exceeds 10 and this loop multiplies each digit of the input number with the i and this product is added and stored in variable sum. charAt() function is used to return a char value at i-1.
This is done in the following way: suppose d represents each digit:
sum=d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9
Next the mod operator is used to get the remainder by dividing the value of sum with 11 in order to find the checksum and stores the result in remainder variable.
If the value of remainder is equal to 10 then use X for 10 and the output will be the 10 digits and the 11th digit checksum (last digit) is X.
If the value of remainder is not equal to 10, then it prints a valid 11-digit number with the given integer as its first 10 digits and the checksum computed by sum % 11 as the last digit.