My code doesn't work, and I'm looking to validate credit card numbers using the Luhn check. I'm stuck and unsure what else it is that i need to do.
package validatecc1;
import java.util.*; // Imports objects such as Scanner.
public class ValidateCC1 {
public static final int INVALID = -1;
public static final int VISA = 0;
public static final int MASTERCARD = -1;
public static String [] cardNames =
{
"Visa Card",
"Mastercard Card",
};
// Method to test that digits are only entered.
private static String getDigitsOnly (String s)
{
StringBuffer digitsOnly = new StringBuffer ();
char c;
for (int i = 0; i < s.length (); i++)
{
c = s.charAt (i);
if (Character.isDigit (c))
{
digitsOnly.append (c);
}
}
return digitsOnly.toString ();
}
// Method to run the Luhn check.
public static boolean isValid(String cardNumber)
{
String digitsOnly = getDigitsOnly(cardNumber);
int sum = 0;
int digit = 0;
int addend = 0;
boolean timesTwo = false;
for (int i = digitsOnly.length () - 1; i >= 0; i--) {
digit = Integer.parseInt (digitsOnly.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;
}
// Method to find the Sum of Even places in reverse.
public static int sumOfDoubleEvenPlace(String cardNumber)
{
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0)
{
start = digits.length() - 1;
}
else
{
start = digits.length() - 2;
}
while (start != 0)
{
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
// Method to
public static int getDigit(int number)
{
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(String cardNumber)
{
int result = 0;
while (number != 0)
{
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d)
{
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d)
{
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k)
{
String size = Long.toString(number);
if (size.length() <= k)
{
return number;
}
else
{
return Long.parseLong(size.substring(0, k));
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number))
{
System.out.println(number + " is valid");
}
else
{
System.out.println(number + " is invalid");
}
}
}