daily pastebin goal
7%
SHARE
TWEET

Untitled

a guest May 16th, 2018 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class MaximaBarcodeCheckDigit extends ModulusCheckDigit {
  2.  
  3.     private static final int[] POSITION_WEIGHT = new int[] {3, 1};
  4.  
  5.     /** Singleton Luhn Check Digit instance */
  6.     public static final CheckDigit MAXIMA_CHECK_DIGIT = new MaximaBarcodeCheckDigit();
  7.  
  8.     public MaximaBarcodeCheckDigit() {
  9.         super(10);
  10.     }
  11.  
  12.     @Override
  13.     protected int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException {
  14.         int weight = POSITION_WEIGHT[rightPos % 2];
  15.         int weightedValue = (charValue * weight);
  16.         if(weightedValue > 9){
  17.             weightedValue = 1 + (weightedValue % 10);
  18.         }
  19.         return weightedValue;
  20.     }
  21.  
  22.     @Override
  23.     protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException {
  24.         if (Character.isLetter(character)) {
  25.             return (int) character;
  26.         } else if(Character.isDigit(character)){
  27.             return Character.getNumericValue(character);
  28.         } else {
  29.             throw new CheckDigitException("Invalid Character[" +
  30.                     leftPos + "] = '" + character + "'");
  31.         }
  32.     }
  33.  
  34.     /**
  35.      * Calculate the modulus for a code.
  36.      *
  37.      * @param code The code to calculate the modulus for.
  38.      * @param includesCheckDigit Whether the code includes the Check Digit or not.
  39.      * @return The modulus value
  40.      * @throws CheckDigitException if an error occurs calculating the modulus
  41.      * for the specified code
  42.      */
  43.     protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
  44.         int total = 0;
  45.         for (int i = 0; i < code.length(); i++) {
  46.             int lth = code.length() + (includesCheckDigit ? 0 : 1);
  47.             int leftPos  = i + 1;
  48.             int rightPos = lth - i;
  49.             int charValue = toInt(code.charAt(i), leftPos, rightPos);
  50.             total += weightedValue(charValue, leftPos, rightPos);
  51.         }
  52.         if (total == 0) {
  53.             throw new CheckDigitException("Invalid code, sum is zero");
  54.         }
  55.         return (10 - (total % 10)) % 10;
  56.     }
  57.  
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top