
Write a JAVA program to validate the credit card numbers using Luhn Check algorithm. You will need to search the Internet to understand how the algorithm works.

Hi Friend,
Try the following code:
import java.util.*;
public class CheckCreditCardNumber {
public static boolean isValid (String cardNumber) {
int sum = 0;
int digit = 0;
int addend = 0;
boolean timesTwo = false;
StringBuffer buffer = new StringBuffer ();
char c;
for (int i = 0; i < cardNumber.length (); i++) {
c = cardNumber.charAt (i);
if (Character.isDigit (c)) {
buffer.append (c);
}
if (Character.isLetter (c)) {
System.out.println("Enter only numbers!");
System.exit(0);
}
}
String st=buffer.toString ();
for (int i = st.length () - 1; i >= 0; i--) {
digit = Integer.parseInt (st.substring (i, i + 1));
if (timesTwo){
addend = digit * 2;
if (addend > 9) {
addend -= 9;
}
}
else {
addend = digit;
}
sum += addend;
timesTwo = !timesTwo;
}
int modulus = sum % 10;
return modulus == 0;
}
public static void main (String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter Credit Card Number: ");
String cardNumber = input.nextLine();
boolean valid = CheckCreditCardNumber.isValid(cardNumber);
if(valid){
System.out.println ("Credit Card Number is Valid");
}
else{
System.out.println ("Invalid Credit Card Number!");
}
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.