Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MaximaBarcodeCheckDigit extends ModulusCheckDigit {
- private static final int[] POSITION_WEIGHT = new int[] {3, 1};
- /** Singleton Luhn Check Digit instance */
- public static final CheckDigit MAXIMA_CHECK_DIGIT = new MaximaBarcodeCheckDigit();
- public MaximaBarcodeCheckDigit() {
- super(10);
- }
- @Override
- protected int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException {
- int weight = POSITION_WEIGHT[rightPos % 2];
- int weightedValue = (charValue * weight);
- if(weightedValue > 9){
- weightedValue = 1 + (weightedValue % 10);
- }
- return weightedValue;
- }
- @Override
- protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException {
- if (Character.isLetter(character)) {
- return (int) character;
- } else if(Character.isDigit(character)){
- return Character.getNumericValue(character);
- } else {
- throw new CheckDigitException("Invalid Character[" +
- leftPos + "] = '" + character + "'");
- }
- }
- /**
- * Calculate the modulus for a code.
- *
- * @param code The code to calculate the modulus for.
- * @param includesCheckDigit Whether the code includes the Check Digit or not.
- * @return The modulus value
- * @throws CheckDigitException if an error occurs calculating the modulus
- * for the specified code
- */
- protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
- int total = 0;
- for (int i = 0; i < code.length(); i++) {
- int lth = code.length() + (includesCheckDigit ? 0 : 1);
- int leftPos = i + 1;
- int rightPos = lth - i;
- int charValue = toInt(code.charAt(i), leftPos, rightPos);
- total += weightedValue(charValue, leftPos, rightPos);
- }
- if (total == 0) {
- throw new CheckDigitException("Invalid code, sum is zero");
- }
- return (10 - (total % 10)) % 10;
- }
- }
Add Comment
Please, Sign In to add comment