Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. /*
  2. This program takes 11 digits of a UPC(Universal Product Code) number and generates the 12th.
  3. A UPC number is the number under the barcode on products in some countries,
  4. not all countries use this number.
  5. */
  6.  
  7. public class UPC {
  8. public static void main(String[] args){
  9. System.out.println(findValidUPC("1234567"));
  10. }
  11. private static int[] turnIntoValidUPC(String UPCString){
  12. int expectedUPCLength = 11;
  13. int[] UPCArray = new int[expectedUPCLength];
  14. int UPCLength = UPCString.length();
  15.  
  16. //If the UPC is shorter than the expected 11 digits, put zeroes in front of the UPC until
  17. //it is 11 digits long
  18. int counter = 0;
  19. while(UPCLength < expectedUPCLength){
  20. UPCArray[counter] = 0;
  21. UPCLength++;
  22. counter++;
  23. }
  24.  
  25. //After putting the zeroes in front, copy the rest of the UPC into the array
  26. int stringCounter = 0;
  27. while(counter != expectedUPCLength){
  28. int currentNumber = Integer.parseInt(UPCString.charAt(stringCounter) + "");
  29. UPCArray[counter] = currentNumber;
  30. stringCounter++;
  31. counter++;
  32. }
  33. return UPCArray;
  34. }
  35. private static int findValidUPC(String UPCString){
  36. int[] UPCArray = turnIntoValidUPC(UPCString);
  37. int sumOfOddPlaces = 0;
  38. int sumOfEvenPlaces = 0;
  39.  
  40. //Loop through the UPC array and add the even and odd spots together
  41. for(int counter = 0; counter < 11; counter++){
  42. if(counter % 2 == 0){
  43. sumOfOddPlaces += UPCArray[counter];
  44. }
  45. else{
  46. sumOfEvenPlaces += UPCArray[counter];
  47. }
  48. }
  49. //Math to calculate the last digit
  50. int lastUPCDigit = sumOfOddPlaces * 3 + sumOfEvenPlaces;
  51. lastUPCDigit = lastUPCDigit % 10;
  52. if(lastUPCDigit == 0){
  53. return 0;
  54. }
  55. return 10 - lastUPCDigit;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement