Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This program takes 11 digits of a UPC(Universal Product Code) number and generates the 12th.
- A UPC number is the number under the barcode on products in some countries,
- not all countries use this number.
- */
- public class UPC {
- public static void main(String[] args){
- System.out.println(findValidUPC("1234567"));
- }
- private static int[] turnIntoValidUPC(String UPCString){
- int expectedUPCLength = 11;
- int[] UPCArray = new int[expectedUPCLength];
- int UPCLength = UPCString.length();
- //If the UPC is shorter than the expected 11 digits, put zeroes in front of the UPC until
- //it is 11 digits long
- int counter = 0;
- while(UPCLength < expectedUPCLength){
- UPCArray[counter] = 0;
- UPCLength++;
- counter++;
- }
- //After putting the zeroes in front, copy the rest of the UPC into the array
- int stringCounter = 0;
- while(counter != expectedUPCLength){
- int currentNumber = Integer.parseInt(UPCString.charAt(stringCounter) + "");
- UPCArray[counter] = currentNumber;
- stringCounter++;
- counter++;
- }
- return UPCArray;
- }
- private static int findValidUPC(String UPCString){
- int[] UPCArray = turnIntoValidUPC(UPCString);
- int sumOfOddPlaces = 0;
- int sumOfEvenPlaces = 0;
- //Loop through the UPC array and add the even and odd spots together
- for(int counter = 0; counter < 11; counter++){
- if(counter % 2 == 0){
- sumOfOddPlaces += UPCArray[counter];
- }
- else{
- sumOfEvenPlaces += UPCArray[counter];
- }
- }
- //Math to calculate the last digit
- int lastUPCDigit = sumOfOddPlaces * 3 + sumOfEvenPlaces;
- lastUPCDigit = lastUPCDigit % 10;
- if(lastUPCDigit == 0){
- return 0;
- }
- return 10 - lastUPCDigit;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement