I know that UPC codes have a check digit and how to use this check digit to see if the code is valid.
If the code is not valid, my program needs to tell me where the error is. I know it can be done, but how? I need to detect single replacement errors (e.g., typing a 5 in the place of a 2) and transposition errors (e.g., typing 12 instead of 21).
Seems simple but I can't figure it out.
The following code will detect errors in a UPC-A code (12-digit) when considered a String
(recommended way).
String upc = "074985003004"; // UPC as a string
int sum = 0;
for(int i = 0; i < a.length(); i++) {
sum += (i%2==0) ? (3*(upc.charAt(i)-48)) : (upc.charAt(i)-48);
}
if (sum % 10 == 0) {
System.out.println("true");
} else {
System.out.println("false");
}
Alternatively, a long
can be used in the following code: (Note: the leading zero's must be removed.)
long upc = 74985003004L; // omit leading zeros;
int sum =0;
for(int i=0; i < 12; i++) {
sum += (i%2 == 0) ? (upc % 10) : (sum += 3*(upc % 10));
upc /= 10;
}
if (sum % 10 == 0) {
System.out.println("true");
} else System.out.println("false");
It is usually best to validate the UPC code before testing. i.e. check to make sure it contains the correct number of digits and only the digits 0-9. As mentioned in the link: https://en.wikipedia.org/wiki/Universal_Product_Code, UPC-A detects 100% of single digit errors and 90% of 2-digit transposition errors.
*UPC does not support error correction. However, if you know which digit is incorrect, you can just try all 10 possible values for that digit until no errors are detected (a valid UPC code).