Java Reference
In-Depth Information
22 verifyButton = new JButton("Verify CC Number");
23
24 frame = new JFrame("Credit card number verifier");
25 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26 frame.setSize( new Dimension(350, 100));
27 frame.setLayout( new FlowLayout());
28 frame.add(numberField);
29 frame.add(verifyButton);
30 frame.add(validLabel);
31 frame.setVisible( true );
32 }
33 }
Now let's write a second version of the GUI that listens for action events on the
Verify CC Number button. The code to validate credit card numbers is complex
enough to be its own method. The code will loop over each digit, starting from the
extreme right, doubling the digits at even indexes and splitting doubled numbers of
10 or larger into separate digits before adding them to the total. We can achieve this
algorithm by adding the digit / 10 and the digit % 10 to the sum. We can actu-
ally add these same two values to the sum even if the number does not exceed 10,
because for single-digit numbers, digit / 10 is 0 and digit % 10 is the digit
itself. Here is the code that implements the validation:
// returns whether the given string can be a valid Visa
// card number according to the Luhn checksum algorithm
public boolean isValidCC(String text) {
int sum = 0;
for (int i = text.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(text.substring(i, i + 1));
if (i % 2 == 0) { // double even digits
digit *= 2;
}
sum += (digit / 10) + (digit % 10);
}
// valid numbers add up to a multiple of 10
return sum % 10 == 0 && text.startsWith("4");
}
Now that we have a method to tell us whether a given string represents a valid Visa
card number, we can write the code to listen for events. First, we'll modify our class
header:
public class CreditCardGUI2 implements ActionListener {
Search WWH ::




Custom Search