Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A useful technique for catching typing errors is to use a check digit. For examp

ID: 3814414 • Letter: A

Question

A useful technique for catching typing errors is to use a check digit.

For example, International Article Number 13 (EAN 13) uses the last digit (also known as checkdigit) to validate the correctness of the first 12 digits.

For more info on EAN13, see: http://en.wikipedia.org/wiki/International_Article_Number_(EAN) (Links to an external site.)

If EAN13 is 4006381333931 the check code is computed as follows:

The nearest multiple of 10 that is equal or higher than the sum, is 90. Subtract them: 90 - 89 = 1, this is the last digit of the barcode.

Write a Java program that asks the user for a EAN13 and validates it as either correct or incorrect (display a message accordingly). Your program should continue to run, to validate multiple EAN13 numbers, until the user decides to exit the program, by entering 'Q' or 'Quit'.

Your program is allowed to use any of the concepts covered through the first 8 chapters and topics from the appendices from our class text book.

Comment your code and use procedural decomposition problem solving techniques.

Calculation First 12 digits of the barcode 4 0 0 6 3 8 1 3 3 3 9 3 Weights 1 3 1 3 1 3 1 3 1 3 1 3 Multiplied by weight 4 0 0 18 3 24 1 9 3 9 9 9 Sum 89

Explanation / Answer

Save in file EANChecker.java

import java.util.Scanner;


public class EANChecker {

private static int getNearest10Multiple(int n)
{
int rem = n%10;
if (rem < 5){
return n - rem;
}
return n + (10 - rem);
}
  
private static boolean isValidEAN(String s)
{
int ean = 0;
for(int i = 0; i < s.length()-1; i++)
{
int num = Integer.parseInt(String.valueOf(s.charAt(i)));
if (i %2 == 0)
{
ean += num;
}
else
{
ean += 3*num;
}
}
  
int next10Mult = getNearest10Multiple(ean);
return Math.abs(next10Mult - ean) == Integer.parseInt(String.valueOf(s.charAt(s.length()-1)));
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
  
String ean;
while(true)
{
System.out.print("Enter a EAN12 number to validate. Enter 'Q' or 'Quit' to quit: ");
ean = sc.next();
if (ean.equals("Q") || ean.equals("Quit"))
{
break;
}
  
if (isValidEAN(ean))
{
System.out.println("Correct EAN13 number.");
}
else
{
System.out.println("Incorrect EAN13 number.");
}
}
sc.close();
}
}

Sample output

Enter a EAN12 number to validate. Enter 'Q' or 'Quit' to quit: 4006381333931
Correct EAN13 number.
Enter a EAN12 number to validate. Enter 'Q' or 'Quit' to quit: 4006381333932
Incorrect EAN13 number.
Enter a EAN12 number to validate. Enter 'Q' or 'Quit' to quit: Q

Please give positive feedback if this answered your question.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote