Search code examples
javafor-loopmathematical-expressions

Check if string is following ISBN-13 in Java


Im trying to check if a string (important that it is a string) that im reading is correct accoring to the rules of ISBN-13. I found a formula

For example, the ISBN-13 check digit of 978-0-306-40615-?

is calculated as follows:

s = 9×1 + 7×3 + 8×1 + 0×3 + 3×1 + 0×3 + 6×1 + 4×3 + 0×1 + 6×3 + 1×1 + 5×3
  =   9 +  21 +   8 +   0 +   3 +   0 +   6 +  12 +   0 +  18 +   1 +  15
  = 93
93 / 10 = 9 remainder 3
10 –  3 = 7`

My problem is i don't know how to multiply one number with 1 and every other with 3 ? Im guessing a for-loop but i don't know how to start.


Solution

  • You have 6 pairs of (even,odd) numbers, so go through them pairwise.

        for (i = 0; i < 6; i++) {
        even += array[2*i];
        odd += array[2*i+1]*3;
        }
        checkbit = 10 - (even+odd)%10;