-
-
Save cwake/e2f694e8e7bbf033d140 to your computer and use it in GitHub Desktop.
Java program that asks the user for a EAN13 and validates it as either correct or incorrect.
This file contains 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.security.InvalidAlgorithmParameterException; | |
import java.util.Scanner; | |
/** | |
* @version 1 | |
* @author ChloeWake,Imbuhira | |
* | |
*/ | |
public class EAN13 { | |
public static void main (String[] args){ | |
String input = GetInput(); //get input from the user | |
if (input.length() < 13) { //check to see if the input is too short | |
try { | |
throw new InvalidAlgorithmParameterException("That's not a long enough barcode! Give me the rest of the digits!"); | |
} catch (InvalidAlgorithmParameterException e) { | |
e.printStackTrace(); | |
return; | |
} | |
} | |
if (input.length() > 13 ) { //check to see if the input is too long | |
try{ | |
throw new InvalidAlgorithmParameterException("That's too long! You only need 13 digits!"); | |
} catch (InvalidAlgorithmParameterException e){ | |
e.printStackTrace(); | |
return; | |
} | |
} | |
int actualChecksum = new Integer(input.substring(12, 13)); | |
int ans = checkSum(input.substring(0, 12)); //pass that input to the checkSum function | |
System.out.println(String.format("Checksum %d matches: %b", ans, ans == actualChecksum)); | |
/** | |
* | |
*/ | |
} | |
public static String GetInput(){ | |
Scanner console = new Scanner(System.in); | |
System.out.println("This program will take the first 12 digits of a EAN13 barcode and compute the check number at the end of the code."); | |
System.out.println("Please enter a EAN13 code: "); | |
String EanCode = console.next(); | |
return EanCode; | |
} | |
public static int checkSum (String input) { | |
int evens = 0; //initialize evens variable | |
int odds = 0; //initialize odds variable | |
int checkSum = 0; //initialize the checkSum | |
for (int i = 0; i < input.length(); i++) { | |
//check if number is odd or even | |
if (i % 2 == 0) { | |
evens += new Integer(input.substring(i, i+1)); // then add it to the evens | |
} else { | |
odds += new Integer(input.substring(i, i+1)); // else add it to the odds | |
} | |
} | |
odds = odds * 3; //multiply odds by three | |
int total = odds + evens; //sum odds and evens | |
if (total % 10 == 0){ //if total is divisible by ten, special case | |
checkSum = 0;//checksum is zero | |
} else { //total is not divisible by ten | |
checkSum = 10 - (total % 10); //subtract the ones digit from 10 to find the checksum | |
} | |
return checkSum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment