请查看我预期输出的pseudo code。
经过单独测试,我设法让Luhn算法工作,并在FAILED时抛出无效异常。
这是我的代码:
public boolean checkCreditCard(String strCardNumber, double amount, String luhnStatus)
throws ExpiredCreditCardException, InvalidCreditCardException,
StolenCreditCardException {
if(luhnStatus.equals("PASSED")) {
if() { // missing condition for expired
throw new ExpiredCreditCardException();
} else if() { // missing condition for stolen
throw new StolenCreditCardException();
}
} else if(luhnStatus.equals("FAILED")) { // invalid
throw new InvalidCreditCardException();
} else {
payItem(amount);
System.out.print("Thank you for shopping with us!");
}
return true;
}
但是,我不知道如何在if-statements中设置过期和被盗异常的条件,如我的伪代码中所预期的那样。
答案 0 :(得分:1)
对于两个if
语句,为每个类似于isExpired(String strCardNumber)
或isStolen(String strCardNumber)
的方法定义一个返回布尔值的方法。这些方法可以遍历各自文件中的条目,如果找到匹配项,则返回true。然后你的代码变成:
if (isExpired(strCardNumber)) {
throw new ExpiredCreditCardException();
} else if (isStolen(strCardNumber)) {
throw new StolenCreditCardException();
}
我还建议,如果值luhnStatus
没有其他值使用布尔值,可以更恰当地称为isValidNumber
或类似的东西。如果不超过两个值PASSED
和FAILED
,则永远不会达到payItem
块。要解决此问题,您可以将payItem
块放在两个if
语句之后,因为如果发生异常,它将被跳过。
示例伪代码ifExpired
方法:
private boolean isExpired(String strCardNumber) {
for each card number in expired card numbers:
if strCardNumber.equals(current number of iteration):
return true;
after iteration, return false as the value was not contained.
}
答案 1 :(得分:1)
在阅读XML文件时,您必须在List中存储每种类型信用卡(被盗或过期)的条目。
以下是part-pseudocode,part-java:
List<String> expiredCCList = new ArrayList<String>();
while (reading_CC_Expired.xml) {
String expiredCC = readEntryFromExpiredXML();
expiredCCList.add(expiredCC);
}
List<String> stolenCCList = new ArrayList<String>();
while (reading_CC_Stolen.xml) {
String stolenCC = readEntryFromStolenXML();
stolenCCList.add(stolenCC);
}
填充这些列表后,您可以像这样调用您的代码:
public boolean checkCreditCard(String strCardNumber, double amount, String luhnStatus) ExpiredCreditCardException, InvalidCreditCardException, {
if(luhnStatus.equals("PASSED")) {
if(expiredCCList.contains(strCardNumber)) {
throw new ExpiredCreditCardException();
} else if(stolenCCList.contains(strCardNumber) {
throw new StolenCreditCardException();
}
} else if(luhnStatus.equals("FAILED")) { // invalid
throw new InvalidCreditCardException();
} else {
payItem(amount);
System.out.print("Thank you for shopping with us!");
}
return true;
}
我在Gist
上为您留下了一段代码段