Created
April 16, 2015 19:45
-
-
Save jonathan-irvin/5205e2d0beee7697cb46 to your computer and use it in GitHub Desktop.
Valid UPC Checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class checkUPCDigits { | |
public static int[] splitNumberIntoArray(long NumberToBeSplit){ | |
int i = 0; | |
int[] Array = new int[12]; | |
int lastDigit; | |
while (NumberToBeSplit > 0){ | |
lastDigit = (int) (NumberToBeSplit % 10); | |
NumberToBeSplit = NumberToBeSplit / 10; | |
Array[i] = lastDigit; | |
i++; | |
} | |
return Array; | |
} | |
public static int sumOfOddArrayIndexes(int[] value){ | |
int sum=0; | |
for(int i=1;i<value.length;i++){ | |
if(i%2!=0){ | |
sum = sum+value[i]; | |
} | |
} | |
return sum; | |
} | |
public static int sumOfEvenArrayIndexes(int[] value){ | |
int sum=0; | |
for(int i=1;i<value.length;i++){ | |
if(i%2==0){ | |
sum = sum+value[i]; | |
} | |
} | |
return sum; | |
} | |
public static boolean CalculatedCheckDigitMatchesActual(long a){ | |
int[] upcArray = splitNumberIntoArray(a); | |
int actualCheckDigit = upcArray[0]; | |
int calculatedCheckDigit = ( (sumOfOddArrayIndexes(upcArray) * 3) + sumOfEvenArrayIndexes(upcArray) ) % 10; | |
if(calculatedCheckDigit != 0){ | |
calculatedCheckDigit = 10 - calculatedCheckDigit; | |
} | |
if(calculatedCheckDigit == actualCheckDigit){ | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
public static boolean isValidUPC(long a){ | |
if(CalculatedCheckDigitMatchesActual(a)){ | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
public static void main(String[] args) { | |
Scanner userInput = new Scanner(System.in); | |
System.out.println("Enter UPC: "); | |
long inputUPC = userInput.nextLong(); | |
if(isValidUPC(inputUPC)){ | |
System.out.println("UPC "+inputUPC+ " is valid."); | |
}else{ | |
System.out.println("UPC "+inputUPC+ " is not valid."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment