// Stuart Reges handout #12 // 10/22/04 // // This program prompts the user for all but the last digit of a credit card // and tells you what the last digit should be for the card to be legal. // This is an implementation of the Luhn algorithm. public class CreditCard { public static void main(String[] args) { giveIntro(); Scanner console = new Scanner(System.in); System.out.print("partial card # (all but last digit)? "); String number = console.nextLine(); System.out.println("The last digit should be " + lastDigitFor(number)); } // Explains the program to the user. public static void giveIntro() { System.out.println("This program will tell you the last digit of a"); System.out.println("credit card (assuming it is legal). Please"); System.out.println("enter all but the last digit."); System.out.println(); } // 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. The method ignores non-digit characters like dashes and // spaces. public static int lastDigitFor(String partialCard) { int multiplier = 2; int sum = 0; for (int i = partialCard.length() - 1; i >= 0; i--) if (Character.isDigit(partialCard.charAt(i))) { int next = digitFor(partialCard.charAt(i)) * multiplier; sum += next/10 + next % 10; if (multiplier == 2) multiplier = 1; else multiplier = 2; } return 10 - sum % 10; } // This method expects a digit character like '0', '1', ..., '9'. It // returns the int equivalent of the digit. public static int digitFor(char ch) { return ch - '0'; } }
Stuart Reges
Last modified: Fri Oct 22 10:51:19 PDT 2004