// Method for verifying a credit card number: // 1. Starting with the second digit from the right, // double every other digit // 2. Break into digits, and add the digits together // 3. Result must end with 0 (e.g 70) import java.util.*; public class Credit { public static void main(String[] args) { // prompt the user for a credit card number Scanner console = new Scanner(System.in); System.out.print("Enter credit card number: "); String number = console.next(); // check to see if the credit card number is valid System.out.println("Checking credit card number '" + number + "'"); int sum = 0; // Add up the digits formed by doubling every other digit for (int i=number.length()-2; i>=0; i = i-2) { char c = number.charAt(i); int n = 2 * Character.getNumericValue(c); sum = sum + n/10 + n%10; // Break into two digits and add System.out.println("c: " + c + ", n: " + n + ", sum: " + sum); } // Add the remaining digits for (int i=number.length()-1; i>=0; i = i-2) { char c = number.charAt(i); int n = Character.getNumericValue(c); sum = sum + n; System.out.println("c: " + c + ", n: " + n + ", sum: " + sum); } System.out.println(); if (sum % 10 == 0) { System.out.println("** Credit card number is valid."); } else { System.out.println("** Credit card number is NOT valid!"); } } }