【问题标题】:Why does my code ignore the Exception?为什么我的代码忽略异常?
【发布时间】:2018-09-07 19:14:16
【问题描述】:

我的代码应该使在 discountCode 字符串中输入除字母或“$”以外的任何内容都会导致抛出异常,但这不会发生。用户可以键入任何内容,但仍然不会收到异常消息。 非常感谢任何帮助,谢谢。

private String normalizeDiscountCode(String discountCode) {
  String upperDiscountCode = discountCode.toUpperCase();

    for (char i : upperDiscountCode.toCharArray()) {
      if (Character.isLetter(i) || i == '$') {
        return upperDiscountCode;
      } else {
        throw new IllegalArgumentException("Invalid discount code");
        }
    }
    return upperDiscountCode;
  }

  public void applyDiscountCode(String discountCode) {
    this.discountCode = normalizeDiscountCode(discountCode);
  }
}

【问题讨论】:

  • 您在第一次迭代中returning。
  • 尝试将"123" 作为参数传递
  • 谢谢,我应该如何继续下去?
  • 还可以考虑使用与 IllegalArgumentException 不同的异常:stackoverflow.com/questions/15208544/…
  • 只有第一个字符不满足条件,你的代码才会失败。将 return upperDiscountCode; 替换为 continue 以使您的代码按原样工作。

标签: java arrays object if-statement illegalargumentexception


【解决方案1】:

Java 8 版本:

private String normalizeDiscountCode(String discountCode) {
    String upperDiscountCode = discountCode.toUpperCase();
    if (upperDiscountCode.chars()
            .allMatch(c -> Character.isLetter(c) || c == '$')) {
        return upperDiscountCode;
    }
    throw new IllegalArgumentException("Invalid discount code");
}

【讨论】:

    【解决方案2】:

    试试这个

    if(!Character.isLetter(i) && i != '$') {
        throw new IllegalArgumentException("Invalid discount code");
    }
    return upperDiscountCode;
    

    ..尽管我仍然对您在第 6 行通过返回 upperDiscountCode 来完成的操作感到有些困惑,如果第一个字符是字母或“$”,它应该只返回,因此不检查任何其他字母.

    【讨论】:

    • 这正是重点。 return 语句是错误,应该删除。
    • 我觉得不是&&,应该是||还是不是?
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2015-12-14
    • 2011-12-01
    • 1970-01-01
    • 2021-12-14
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多