Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
Seth Kroger
56,413 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.