
// CheckISBN.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Check whether the given ten-digit number string
   is a valid ISBN.

   https://en.wikipedia.org/wiki/ISBN
    -- see "ISBN-10 check digits" section

   Usage:
     > compile CheckISBN.java
     > run CheckISBN <ISBN string>
   e.g.
     > run CheckISBN 007462542X

*/

import java.util.*;
import java.io.*;


public class CheckISBN
{
  private static final int ISBN_LEN = 10;


  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run CheckISBN <ISBN string>");
      System.out.println("   e.g. 007462542X");
      return;
    }
    System.out.print("\"" + args[0] + "\" : ");

    if (isValidISBN(args[0]))
      System.out.println("Valid ISBN");
    else
      System.out.println("Invalid");
  } /* main */


  private static boolean isValidISBN(String isbn)
  {
    if (isbn.length() != ISBN_LEN) {
      System.out.print(" length != " + ISBN_LEN + " ");
      return false;
    }

    // Compute weighted sum of first 9 digits
    int sum = 0;
    for (int i = 0; i < ISBN_LEN-1; i++) {
      int digit = isbn.charAt(i) - '0';
      if ((0 > digit) || (9 < digit) )
        return false;
      sum += (digit * (10 - i));
    }

    // Check last digit
    char last = isbn.toUpperCase().charAt(ISBN_LEN-1);
    if ((last != 'X') && ((last < '0') || (last > '9') ))
      return false;

    // If last digit is 'X', add 10, else add value
    sum += ((last == 'X') ? 10 : (last - '0'));

    // is weighted sum divisible by 11?
    return (sum % 11 == 0);
  } /* isValidISBN */

}  // end of CheckISBN class