java - 捕获异常后如何在 for 循环中不增加?

标签 java

这是我的老师的提示:

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/

相关文章:

java - 错误 : the method sort (Comparable []) in the type Selection is not applicable for the arguments (int[])

旋转设备时 ScrollView 中出现 java.lang.IllegalStateException

java - 使用 Drools 规则进行实体验证

java - 在哪里编写安装矩阵工具包的代码?

java - 唯一键约束

java - 我怎样才能在Java的方法中播放音频文件,但是当再次调用该方法时,之前的音频文件会停止播放?

java - 删除 Map<Long, List<Object>> 的条目

java - 尝试创建数组列表的数组列表,但遇到此错误 :

剩余大量内存时出现 java.lang.OutOfMemoryError (94GB/200GB Xmx)

java - 使用 Windowbuilder 和 Java 显示双重使用文本?