-1

Quoted from my assignment: The objectives of this question are (a) to practice selection structure (b) to apply iteration structure (c) to manipulate string

do {
    System.out.print("Enter MC for MasterCard or VISA for VISA card: ");
    cardType = scn.next();
} while (!cardType.equals("MC") && !cardType.equals("VISA"));
if (cardType.equals("MC")) {
    do {
        System.out.print("Enter MasterCard card no.: "); // Get input:
                                                            // mastercard
                                                            // number
        cardNo = scn.nextLong();
        cardLength = Long.toString(cardNo).length(); // Get length of
                                                        // mastercard
                                                        // number input
        dbUserPrefix = cardNo / java.lang.Math.pow(10, 14);
        intUserPrefix = (int) dbUserPrefix;
        for (int i = 0; i <= 5; i++) {// for validating prefix
            // 4 possibilities
            if (intUserPrefix == cardPrefix[i]) {
                if (cardLength == 16) { // Prefix & length correct                      break;
                } else { // Prefix correct, length wrong
                    state = 1;
                    break;
                }
            } else {
                if (cardLength == 16) { // Prefix wrong, length correct                     state = 2;
                } else { // Prefix & length incorrect
                    state = 3;
                }
            }
        }
        if (state == 0) {
            System.out.println("SUCESS");
        } else if (state == 1) {
            System.out.println("Your length of card number is incorrect.");
        } else if (state == 2) {
            System.out.println("Your card prefix is incorrect.");
        } else {
            System.out.println("Your card prefix and length of card number is incorrect.");
        }
        break;
    } while (cardLength != 16);
}

The main thing I want here is the program to validate that the right Prefix of a credit card is 51,52,53,54 or 55. and the right length to be 16 (number of digits). If validation fails, the error must be printed out. Problem is that other than prefix==51, the rest of the prefix i tried results in state==2.

4

1 回答 1

2

我会以不同的方式解决这个问题。你把你的输入(卡号)当作一个长的。我认为如果你把它当作一个字符串来做这种验证会更容易。

要验证长度,其中cardNum是 String 类型:

boolean isValidLength = (cardNum.length() == 16);

获取前缀:

String prefix = cardNum.substring(0,2); // gets first two digits of cardNum

为了验证,我将所有有效前缀放在一个列表中并调用.contains()

List<String> validPrefixes = new ArrayList<String>();
validPrefixes.add("52");
// ... etc

boolean isValidPrefix = validPrefixes.contains(prefix);

然后你的逻辑会是这样的:

  1. 提示用户输入号码
  2. 将输入作为字符串
  3. 检查输入长度是否正确;如果不返回错误
  4. 检查前缀是否正确;如果不返回错误
  5. 返回成功
于 2012-08-16T20:44:31.247 回答