这是我的老师的提示:
Put the TRY block with the CATCH clause INSIDE THE FOR/WHILE LOOP so if the SPECIFIC exception is thrown from the constructor , you will display an error message, and NOT INCREMENT the counter.
这是我的构造函数和这部分的代码:
public CreditCardNumber(String id, String accNum) {
this();
if (id == null || accNum == null || id.length() != 6 || accNum.length() != 9 ||
isDigit(id) == false || isDigit(accNum) == false) {
throw new IllegalArgumentException("Either parameter is null or has incorrect length or doesn't have all digits");
} else {
accountNum = accNum;
issuerId = id;
setCheckDigit();
}
}
///
for (int i = 0; i < arrLength; i++) {
try {
System.out.println("Enter an issuer ID# (6 digits) for element #" + i);
String issuerId = scanner.next();
System.out.println("Enter an account # (9 digits) for element #" + i);
String accountNum = scanner.next();
CreditCardNumber obj = new CreditCardNumber(issuerId, accountNum);
obj.changeId(issuerId);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Input, Try Again!")
continue;
}
}
现在我遇到的麻烦是如何实现此代码,以便在捕获异常后,代码重新提示用户输入捕获异常的相同 i 值的值。基本上如何做捕获异常后我不增加循环吗?我尝试继续;方法,编译器说代码无法访问。请帮忙!
最佳答案
不必在 for 循环的第三部分中使用一元 ++
运算符递增 i
,只需在 try block 的末尾执行此操作即可:
for (int i = 0; i < arrLength;) { // removed here
try {
System.out.println("Enter an issuer ID# (6 digits) for element #" + i);
String issuerId = scanner.next();
System.out.println("Enter an account # (9 digits) for element #" + i);
String accountNum = scanner.next();
CreditCardNumber obj = new CreditCardNumber(issuerId, accountNum);
obj.changeId(issuerId);
i++; // added here
} catch (IllegalArgumentException e) {
System.out.println("Invalid Input, Try Again!"); // don't throw just print
}
}
此外,我建议以
的形式替换构造函数中的 boolean 检查if(variable == false){...}
仅
if(!variable){...}
关于java - 捕获异常后如何在 for 循环中不增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50936707/