-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUPCMain.java
More file actions
100 lines (83 loc) · 2.73 KB
/
UPCMain.java
File metadata and controls
100 lines (83 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//Enter a 12-digit number such as "0123456789012" and this app
//will compute the check digit to verify if the number is a
//valid UPC-A barcode. The left and right data strings are also
//extracted for use in creating a barcode.
//Emerson Racca
//I apologize for the messy code. It's meant for further development.
import java.util.Scanner;
public class UPCMain{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int length;
String upc;
while(true){
try{
System.out.println();
System.out.print("Enter a 12 digit UPC number: ");
upc = reader.nextLine();
upc = upc.trim();
length = upc.length();
int check = 0;
boolean goodUPC = true;
char cDigit;
int iDigit;
if(length == 12){
for(int c = 0; c < 12; c++){
cDigit = upc.charAt(c);
iDigit = (int) cDigit;
//iDigit = Character.getNumericValue(cDigit);
//System.out.println(iDigit + "");
if(!(iDigit >= 48 && iDigit <=57))
goodUPC = false;
}
}
else{
System.out.println("It must be a string of 12 numbers.");
goodUPC = false;
}
if(goodUPC){ //check digit check.
String cDig;
int iDig;
int oddSum = 0;
int evenSum = 0;
int checkDigitComputed = -1;
int checkDigitGiven = -1;
for(int c = 0; c < 11; c++){ //11th digit
cDig = upc.substring(c, c + 1);
iDig = Integer.parseInt(cDig);
if((c % 2) == 1){ //even although odd location
//System.out.println(iDig + "e");
evenSum = evenSum + iDig;
}
else{
//System.out.println(iDig + "o");
oddSum = oddSum + iDig;
}
}
//System.out.println(evenSum + " e o " + oddSum);
checkDigitComputed = (10 - (((oddSum * 3) + evenSum) % 10)) % 10;
System.out.println(checkDigitComputed + "<-----checkDigitComputed");
checkDigitGiven = Integer.parseInt(upc.substring(11, 12));
System.out.println(checkDigitGiven + "<---------checkDigitGiven");
if(checkDigitComputed == checkDigitGiven)
break;
else{
goodUPC = false;
System.out.println("The check digit does not validate.");
}
}
}
catch(Exception e){
System.out.println("Error. Something went wrong.");
}
//reader.nextLine(); //not necessary
}
System.out.println(upc + " is a valid UPC number");
//get the left 6 digits for the barcode.
String leftData = upc.substring(0, 6); //dumb that endIndex gets 1 less.
System.out.println(leftData + "<---------leftData");
//get right 5 digits
String rightData = upc.substring(6, 11);
System.out.println(rightData + "<----------rightData");
}
}