Validate Card Numbers With The Luhn Check

Validate card-style numbers with the Luhn checksum: double every second digit from the right and require the total to be divisible by ten.

JavaForm Validation

Code

snippet
public class LuhnCheck {

    // Luhn 校验:从右往左隔位翻倍,超过 9 就减 9,总和被 10 整除才合法
    static boolean isValid(String number) {
        int sum = 0;
        boolean doubleIt = false;
        for (int i = number.length() - 1; i >= 0; i--) {
            char c = number.charAt(i);
            if (c == ' ' || c == '-') {
                continue;                       // 容忍常见分隔符
            }
            if (c < '0' || c > '9') {
                throw new IllegalArgumentException("not a digit: " + c);
            }
            int digit = c - '0';
            if (doubleIt) {
                digit *= 2;
                if (digit > 9) {
                    digit -= 9;
                }
            }
            sum += digit;
            doubleIt = !doubleIt;
        }
        return sum % 10 == 0;
    }

    public static void main(String[] args) {
        for (String candidate : new String[] {
                "4539 1488 0343 6467", "4539 1488 0343 6468", "79927398713"}) {
            System.out.println(candidate + " -> " + isValid(candidate));
        }
    }
}

How the snippet works

The moving parts are the class LuhnCheck and the functions isValid and main.

Repetition is confined to for (int i = number.length() - 1; i >= 0; i--) — the rest of the file is straight-line. Invalid states are rejected up front: it throws IllegalArgumentException instead of continuing with bad data.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The main signature reads static boolean isValid(String number)

Start the program and main runs isValid one after another.

Key statements

throw new IllegalArgumentException("not a digit: " + c);
return sum % 10 == 0;
sum += digit;

Interactive Tools for This Topic

FAQ

Does the code validate its input?
Validation comes first — `IllegalArgumentException` marks the failure, before any partial work happens.
How do you run Validate Card Numbers With The Luhn Check?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.