// Stuart Reges handout #12 // 2/4/05 // // This program tells you what the last digit of a credit card should be. // This is an implementation of the Luhn algorithm. public class CreditCard { public static void main(String[] args) { String number = "438857511070717"; System.out.println("The last digit should be " + lastDigitFor(number)); } // This method takes a partial credit card number (all but the last // digit) and computes what the last digit should be, returning it // as an int. public static int lastDigitFor(String card) { int multiplier = 2; int sum = 0; for (int i = card.length() - 1; i >= 0; i--) { int next = Character.getNumericValue(card.charAt(i)) * multiplier; sum += next/10 + next % 10; if (multiplier == 2) { multiplier = 1; } else { multiplier = 2; } } return (10 - sum % 10) % 10; } }
Stuart Reges
Last modified: Thur Jan 26 2:15:05 PDT 2006