Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.0 kB
1
Indexable
Never
import java.util.Scanner;

public class CreditCardValidator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your credit card number: ");
        String creditCardNumber = scanner.nextLine();

        if (isValidCreditCard(creditCardNumber)) {
            System.out.println("Credit card number is valid.");
        } else {
            System.out.println("Credit card number is invalid.");
        }
    }

    public static boolean isValidCreditCard(String creditCardNumber) {
        int sum = 0;
        boolean alternate = false;
        for (int i = creditCardNumber.length() - 1; i >= 0; i--) {
            int n = Integer.parseInt(creditCardNumber.substring(i, i + 1));
            if (alternate) {
                n *= 2;
                if (n > 9) {
                    n = (n % 10) + 1;
                }
            }
            sum += n;
            alternate = !alternate;
        }
        return (sum % 10 == 0);
    }
}
Leave a Comment