# Credit card validator

• October 14th, 2010, 10:46 PM
SOK
Credit card validator
Hey All. I am trying to do a credit card validator. We can't use an array so this is what I have done so far. Not working for me unfortunately. I think my algorithm is off.

Code Java:

```import java.util.Scanner;   public class creditCardValid { public static void main(String[] args) {   Scanner input = new Scanner(System.in); int num = 0; int checkDigit; int digit = 0; int digit2 = 0; int digit16; int power = 1; int userInput = 0; int sum = 0; int totalSum = 0;   System.out.print("Enter card number:");   String cardNum = input.next();   if (cardNum.length() < 13 || cardNum.length() > 16) { System.out.println("Invalid card number: Out of range"); } else {   //calculates place value. checkDigit = num % 10; totalSum = checkDigit;   while (power < 16) { digit = num / (power * 10) % 10; digit2 = num / (power * 100) % 10;     digit = (digit * 2) % 16; sum = digit + digit2; totalSum = totalSum + sum;   power = power * 100; }     digit16 = num / 16;     if (totalSum % 10 != 0) { System.out.println("Invalid card number: Fails check algorithm"); } else   { if (num == 51 || num == 52 || num == 53 || num == 54 || num == 55)   System.out.println("Valid MASTERCARD card number");   else if (num == 4)   System.out.println("Valid VISA card number");   else if (num == 34 || num == 37)   System.out.println("Valid AMEX card number ");   else if (num == 300 || num == 301 || num == 302 || num == 303 || num == 304 || num == 305 || num == 36 || num == 38)   System.out.println("Valid DINER CLUB card number");   else if (num == 6001)   System.out.println("Valid DISCOVER card number");   else if (num == 2014 || num == 2149)   System.out.println("Valid ENROUTE card number");   else if (num == 3)   System.out.println("Valid JCB card number");   else if (num == 1800 || num == 2131)   System.out.println("Valid JCB card number");     }   } } }```
• October 15th, 2010, 03:11 AM
JavaPF
Re: Credit card validator
Hello SOK,

One of your problems is here:

Code Java:

``` // calculates place value. checkDigit = num % 10; totalSum = checkDigit;   while (power < 16) { digit = num / (power * 10) % 10; digit2 = num / (power * 100) % 10;   digit = (digit * 2) % 16; sum = digit + digit2; totalSum = totalSum + sum;   power = power * 100; }   digit16 = num / 16;   System.out.println(totalSum);   if (totalSum % 10 != 0) { System.out.println("Invalid card number: Fails check algorithm"); } else```

I added System.out.println(totalSum); so we could see the value. The totalSum value is always 0.

This is why none of your if statements are executed.

Also once cardNum is read in and the length checked, nothing else is done with it...

Hope this helps :)