// This program tells you what the last digit of a credit card should be. // This is an implementation of the Luhn algorithm. import java.util.*; public class CreditCard { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("This program tells you the last digit of a"); System.out.println("credit card."); System.out.println(); System.out.print("leading digits (all but last)? "); String number = console.next(); 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 digit = Character.getNumericValue(card.charAt(i)); int n = digit * multiplier; sum = sum + n / 10 + n % 10; if (multiplier == 2) { multiplier = 1; } else { multiplier = 2; } } return (10 - sum % 10) % 10; } }