引自我的任务:这个问题的目标是 (a)实行选拔结构 (b)应用迭代结构 (c)操纵字符串
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);
}
我想要的主要是验证信用卡的正确前缀是51,52,53,54或55,并且正确长度为16(位数)的程序。如果验证失败,则必须打印出错误。问题是除了前缀== 51之外,我尝试的其余前缀导致状态== 2。
答案 0 :(得分: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);
然后你的逻辑将会是这样的: