The Luhn-10 algorithm is a weighted algorithm. Each digit in the credit card num
ID: 3596745 • Letter: T
Question
The Luhn-10 algorithm is a weighted algorithm. Each digit in the credit card number is multiplied by a weight. These weights are then summed, forming the checksum. The checksum is divided by 10. If the remainder is 0, the credit card number is valid. If the remainder is NOT 0, the user made an error and can be prompted to re-enter their credit card data. The weighting for the Luhn-10 algorithm is as follows:
Beginning with the first (ie leftmost) digit in the credit card, every other number is multiplied by 2. If the product results in a 2 digit number (eg 6 x 2 = 12) then the individual digits (eg 1 and 2) are added to the checksum. The remaining digits of the credit card number are simply added to the checksum. That is, their weight is 1.
Some examples are given below, but this algorithm will work with your Visa or Mastercard number. Try it!
Write a method in java named luhnChecksum which takes an array of integers as an input parameter and returns the integer checksum computed by the above algorithm.
Explanation / Answer
The following code implements the described algorithm. The algorithm accepts a credit card number of length 14,15 or 16 and checks in accordance with the described algorithm. This is because most of the cards have 16 digits but some may have 14 or 15 digits. e.g. American Express cards
Please note:
1. Anything other than digits will be rejected.
2. Also, examples are not provided. Thus, the algorithm is strictly based on the described algorithm
3. javaapplication18 is the name of the class and can be replaced as desired.
package javaapplication18;
import java.util.*;
public class JavaApplication18
{
static int luhnChecksum(int cardNumber[])
{
int checksum=0;
for(int i=0;i<cardNumber.length;i++)
{
if (i%2==1)
{
checksum=checksum+(cardNumber[i]);
}
else if (i%2==0)
{
checksum=checksum+(cardNumber[i]*2);
}
}
return checksum;
}
public static void main(String[] args)
{
int[] cardNumber= new int[16];
String cardString;
Scanner s1=new Scanner(System.in);
System.out.println("Please Enter Your Card Number");
cardString=s1.nextLine();
try
{
if(cardString.length()>=14)
{
for(int i=0;i<cardString.length();i++)
{
cardNumber[i]=Integer.parseInt(cardString.charAt(i)+"");
}
int checksum=luhnChecksum(cardNumber);
if(checksum%10==0)
{
System.out.println("Valid Card Number");
}
else
{
System.out.println("Invalid Card Number");
}
}
else if(cardString.length()>16 || cardString.length()<14)
{
System.out.println("Invalid Card Number Length");
}
}
catch(Exception e){
System.out.println("Please use digits only");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.