为什么我的代码会忽略异常?

时间:2022-06-06 20:18:35

My code should make entering anything other than a letter or a '$' in discountCode String result in throwing an exception however this doesn't happen. The user can type anything and still not receive an exception message. Any help is much appreciated, thanks.

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

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);
  }
}

2 个解决方案

#1


1  

Try this

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

..although I'm still a little confused about what you are trying to accomplish on line 6 by returning the upperDiscountCode, which should just return if the first character is a letter or '$', therefore not checking any other letters.

..尽管我仍然对你要在第6行完成的东西感到有点困惑,因为它返回了upperDiscountCode,如果第一个字符是字母或'$',它应该返回,因此不检查任何其他字母。

#2


2  

Java 8 version:

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");
}

#1


1  

Try this

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

..although I'm still a little confused about what you are trying to accomplish on line 6 by returning the upperDiscountCode, which should just return if the first character is a letter or '$', therefore not checking any other letters.

..尽管我仍然对你要在第6行完成的东西感到有点困惑,因为它返回了upperDiscountCode,如果第一个字符是字母或'$',它应该返回,因此不检查任何其他字母。

#2


2  

Java 8 version:

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");
}