Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static final int INVALID = -1;
    public static final int VISA = 0;
    public static final int MASTERCARD = 1;

    /**
     * Get the Card type returns the credit card type INVALID = -1; VISA = 0;
     * MASTERCARD = 1; AMERICAN_EXPRESS = 2; EN_ROUTE = 3; DINERS_CLUB = 4;
     */
    public static int getCardID(String number) {
        int valid = INVALID;
        String digit1 = number.substring(0, 1);
        String digit2 = number.substring(0, 2);

        if (isNumber(number)) {
            /* ----
             ** VISA  prefix=4
             ** ----  length=13 or 16
             */
            if (digit1.equals("4")) {
                if (number.length() == 13 || number.length() == 16) {
                    valid = VISA;
                }
            } /* ----------
               ** MASTERCARD  prefix= 51 ... 55
               ** ----------  length= 16
               */else if (digit2.compareTo("51") >= 0 && digit2.compareTo("55") <= 0) {
                if (number.length() == 16) {
                    valid = MASTERCARD;
                }
            } /* ----
               ** AMEX  prefix=34 or 37
               ** ----  length=15
              else if (digit2.equals("34") || digit2.equals("37")) {
              if (number.length() == 15) {
                  valid = AMERICAN_EXPRESS;
              }
              }*/
        }
        return valid;

    }

    private static boolean isNumber(String n) {
        try {
            double d = Double.valueOf(n).doubleValue();
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}