Java Java Objects Delivering the MVP Applying a Discount Code

illegealArgumentException

I converted the discount string to an array character and checking if each character is a letter or a '$'. But it throws an illegalArgumentException

public class Order {
  private String itemName;
  private int priceInCents;
  private String discountCode;

  public Order(String itemName, int priceInCents) {
    this.itemName = itemName;
    this.priceInCents = priceInCents;
  }

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

  private String normalizeDiscountCode(String discount)
  {
    char[] discountChar = discount.toCharArray();
    for(char discountLetter: discountChar)
    {
      if(!Character.isLetter(discountLetter) || discountLetter != '$')
      {
        throw new IllegalArgumentException("Invalid discount code");
      }
    }
    return discount.toUpperCase();
  }
}

1 Answer

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,273 Points

In your if statement you are using logical-OR instead of logical-AND. With a '$' character the first part will always be true, since the '$' is not a letter, which makes the whole condition true and throw the exception.