Romain Trost
Romain Trost

Reputation: 13

Why does my code ignore the Exception?

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.

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

Upvotes: 1

Views: 92

Answers (2)

David Conrad
David Conrad

Reputation: 16369

Java 8 version:

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

Upvotes: 2

RecyclingBen
RecyclingBen

Reputation: 310

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.

Upvotes: 1

Related Questions