I've been trying to figure out this Luhns method of validating a Credit Card but I can't seem to figure it out. I NEED to use methods and cannot use arrays so I'm totally stumped.
Here's the Luhns check:
A credit card number must have between 13 and 16 digits. It must start with: ■ 4 for Visa cards ■ 5 for Master cards ■ 37 for American Express cards ■ 6 for Discover cards
- Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
- Now add all single-digit numbers from Step a.
- Add all digits in the odd places from right to left in the card number.
- Sum the results from Step b and Step c.
- If the result from Step d is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.
My issue is that I'm still learning methods (Total beginner. I tried to learn to code once last year and gave up, but I've managed to get this far this time) and I can't figure out how to use these methods to both do step 4 and 5 from the Luhn check.
Could someone please try to help me out? Thank you!!
public static boolean isValid(String x) {
return false; // Stub method
}
public static void AddResults() {
}
public static void OddDigits(String s) {
int sum = 0;
for (int index = 0; index < s.length(); index ++) {
if (index % 2 != 0) {
sum = sum + Character.getNumericValue(s.charAt(index));
}
}
return;
}
public static int DoubleToSingle(int x) { // Adds up the digits in a two-digit number.
if (x < 10) {
return x;
}
else {
int firstDigit = x % 10;
int secondDigit = (int)(x / 10);
return firstDigit + secondDigit;
}
}
public static void Doubling(String s) {
int sum = 0;
for (int index = s.length() - 1; index > 0; index-= 2) {
int parse = Character.getNumericValue(s.charAt(index));
if (parse > 9) {
sum = sum + DoubleToSingle(parse);
}
else {
sum = sum + parse;
}
}
return;
}
public static boolean CheckLength(String s) {
if (s.length() < 13 || s.length() > 16) { // If the cc number is smaller than 13 digits or larger than 16 digits, it's invalid
return false;
}
else {
return true;
}
}
public static String ReadString(Scanner s) { // Creating a string method. (Using it to practice creating methods)
String x = s.nextLine();
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please input a valid Credit Card number: ");
String CC = ReadString(input);
if (isValid(CC) == true) {
System.out.println(CC + " is valid.");
} else {
System.out.println(CC + " is invalid.");
}
input.close();
}