I'm trying to get this ISBN checker to work. I've used the formula from this site and also this site and it seems to work fine except for the ISBN of my Java book. When I compute my book's ISBN (0131496980), it is apparently invalid. I have tried the other codes on both of those sites as well as other books I have at home and there is no problem. Here is my code:
public class DigitExtractor
{
public DigitExtractor(String code)
{
isbn = code;
}
public int nextDigit()
{
// convert to int
digit = isbn.charAt(count) - 48;
count += 1;
return digit;
}
public int getLength()
{
return isbn.length();
}
public String getISBN()
{
return isbn;
}
private String isbn;
private int digit;
private int count;
}
public class ISBNChecker
{
public static void main(String[] args)
{
DigitExtractor myDigit = new DigitExtractor("123456789X");
int sum = 0; // holds the sum
int rem = 0; // holds the remainder
int checkSum = 0; // holds the checkSum value
if (myDigit.getLength() == 10)
{
// extract the next digit and add it to the sum
for (int cnt = 0; cnt < myDigit.getLength() - 1; cnt++)
{
int temp = myDigit.nextDigit() * (myDigit.getLength() - cnt);
sum += temp;
System.out.println(temp);
}
System.out.println("sum: " + sum);
// get the remainder of sum / 11
rem = sum % 11;
System.out.println("remainder: " + rem);
// subtract remainder from 11 to get checkSum
checkSum = 11 - rem;
System.out.println("checksum: " + checkSum);
}
else if (myDigit.getLength() == 13)
{
// extract the next digit and add it to the sum
for (int cnt = 0; cnt < myDigit.getLength() - 1; cnt++)
{
int temp = myDigit.nextDigit();
if ((cnt + 1) % 2 == 0)
{
sum += temp * 3;
System.out.println(temp * 3);
}
else
{
sum += temp;
System.out.println(temp);
}
}
System.out.println("sum: " + sum);
// get the remainder of sum/10
rem = sum % 10;
System.out.println("rem: " + rem);
// subtract remainder from 10 to get checkSum
checkSum = 10 - rem;
System.out.println("checksum: " + checkSum);
}
else
System.out.println("Invalid ISBN");
// check the sum to see if it is valid
if (checkSum < 10 && (myDigit.getISBN().charAt(myDigit.getLength() - 1) == (checkSum + 48)))
System.out.println("Valid ISBN - num");
else if (checkSum >= 10 && (myDigit.getISBN().charAt(myDigit.getLength() - 1) == 'X'))
System.out.println("Valid ISBN - X");
else
System.out.println("Invalid ISBN");
}
}