Check ISBN is valid

Assignment 

Solution

CheckISBN13.java 

importjava.util.Scanner;

public class CheckISBN13 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// read  12 digits

System.out.print(“Enter the first 12 digits of an ISBN-13 as a string: “);

String input = scanner.nextLine();

// check if input is valid

boolean valid = isValid(input);

// if valid

if(valid) {

// calculate digit 13 and sisplay final isbn

int digit = calculateDigit13(input);

String isbn13 = input + digit;

System.out.println(“The ISBN-13 number is “+isbn13);

} else // invalid input

System.out.println(“invalid input”);

scanner.close();

}

// method to calculate if the input is valid or not

public static booleanisValid(String input) {

boolean valid = input.length() == 12; // check valid length

if(valid) {

// check if all are digits

for (int i = 0; i <input.length(); i++) {

char c = input.charAt(i);

if(c < ‘0’ || c > ‘9’) {

valid = false;

break;

}

}

}

return valid;

}

// calculate checksum

public static int calculateDigit13(String input) {

// find sum

int sum = 0;

for (int i = 0; i <input.length(); i+=2) {

sum += Character.getNumericValue(input.charAt(i))

+  3 * Character.getNumericValue(input.charAt(i + 1));

}

// take modulus

sum = sum % 10;

// find digit

int digit = 10 – sum;

// if 10, replace it by 0

if(digit == 10)

return 0;

else

return digit;

}

}