THINK FIRST·CODE LATER

← All labs

Is this card number valid? The Luhn check

Problem

Card numbers (13 to 16 digits) carry a built-in check, the Luhn algorithm:

  1. From the right, double every second digit; if the result has two digits, add them (16 → 1 + 6 = 7).
  2. Add all the results of step 1.
  3. Add all the other digits (first, third… from the right).
  4. The number is valid if the total of steps 2 and 3 is divisible by 10.

The first digits give the brand: 4 Visa, 5 Mastercard, 37 American Express, 6 Discover. Write CardCheck with the methods isValid, sumOfDoubledDigits, digitValue, sumOfOtherDigits, countDigits, prefix(number, k) and brand. The number is a long. main reads numbers until the end of the input. For the input

4388576018410707 4388576018402626 5105105105105100 371449635398431 6011111111111117 4111111111111112 123456

the program prints

4388576018410707: sum 70, valid, Visa
4388576018402626: sum 75, invalid
5105105105105100: sum 20, valid, Mastercard
371449635398431: sum 80, valid, American Express
6011111111111117: sum 30, valid, Discover
4111111111111112: sum 31, invalid
123456: sum 21, invalid

(The numbers used here are published test numbers, not real cards.)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l8-7-data-1.txt

4388576018410707 4388576018402626 5105105105105100 371449635398431 6011111111111117 4111111111111112 123456
What your program must print for l8-7-data-1.txt
4388576018410707: sum 70, valid, Visa
4388576018402626: sum 75, invalid
5105105105105100: sum 20, valid, Mastercard
371449635398431: sum 80, valid, American Express
6011111111111117: sum 30, valid, Discover
4111111111111112: sum 31, invalid
123456: sum 21, invalid

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l8-7-data-1.txt

Windows PowerShell does not understand <:

Get-Content l8-7-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.