Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: Lu Liu
- * Date: 11/8/2015
- * Course Number: CSC-111
- * Course Name: Introduction to Java Programming
- * Problem Number:Problem 6.31(Credit Card Number Validation)
- * Email: lliu0001@student.stcc.edu
- * Problem Description: Credit Card Number Validation
- */
- package chapter06;
- import java.util.Scanner;
- public class CreditCardValidation {
- public static void main(String args[]) {
- final String TITLE = "Credit Card Validator";
- final String CONTINUE_PROMPT = "Do this again? [y/N] ";
- System.out.println("Welcome to " + TITLE);
- Scanner sc = new Scanner(System.in);
- do {
- System.out.println("Enter a credit card number as a long integer: ");
- long ccn = sc.nextLong();
- sc.nextLine();
- if (isValid(ccn))
- System.out.println(ccn + " is valid");
- else
- System.out.println(ccn + " is invalid");
- } while (doThisAgain(sc, CONTINUE_PROMPT));
- sc.close();
- System.out.println("Thank you for using " + TITLE);
- }
- private static boolean doThisAgain(Scanner sc, String prompt) {
- System.out.print(prompt);
- String doOver = sc.nextLine();
- return doOver.equalsIgnoreCase("Y");
- }
- public static boolean isValid(long ccn) {
- if (ccn <= 0)
- return false;
- int size = getSize(ccn);
- if (size < 13 || size > 16)
- return false;
- if (!prefixMatched(ccn, 4) && !prefixMatched(ccn, 5) && !prefixMatched(ccn, 6) && !prefixMatched(ccn, 37))
- return false;
- return (sumOfDoubleEvenPlace(ccn) + sumOfOddPlace(ccn)) % 10 == 0;
- }
- public static int getSize(long d) {
- int count = 0;
- while (d > 0) {
- d = d / 10;
- count++;
- }
- return count;
- }
- public static int sumOfDoubleEvenPlace(long number) {
- int sum = 0;
- while (number > 0) {
- int last2Digits = (int) (number % 100);
- int evenDigit = last2Digits / 10;
- sum += getDigit(2 * evenDigit);
- number = number / 100;
- }
- return sum;
- }
- public static int getDigit(int number) {
- if (number <= 9)
- return number;
- else
- return number / 10 + number % 10;
- }
- public static int sumOfOddPlace(long number) {
- int result = 0;
- while (number > 0) {
- result += (int) (number % 10);
- number = number / 100;
- }
- return result;
- }
- public static boolean prefixMatched(long number, int d) {
- if ((getPrefix(number, 1) == d) || (getPrefix(number, 2) == d))
- return true;
- else
- return false;
- }
- public static long getPrefix(long number, int k) {
- if (getSize(number) < k)
- return number;
- else {
- int size = (int) getSize(number);
- for (int i = 0; i < (size - k); i++) {
- number = number / 10;
- }
- return number;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement