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

Akhil Matabudul
Akhil Matabudul
2,386 Points

Help with task 2 in the first challenge(the one which asks to consider discount codes with only letters or $)

The thing is that I have tried various methods, all of which haven't been showed before in the tutorials (after some personal research), so what I wanted to know is whether anyone has the specific solution required. This would be greatly appreciated since I've been stuck on this for a while now.

Order.java
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 discountCode)
  {
    discountCode = discountCode.toUpperCase();
    if(discountCode.indexOf('$') == -1 || !discountCode.matches("[A-Z]+"))
    {
      throw new IllegalArgumentException("Invalid discount code");
    }
    return discountCode;
  }
}

1 Answer

Mihai Craciun
Mihai Craciun
13,520 Points

The way I solved it is to use the String.toCharArray() to go through every character in the code and to check if there are not characters that are not letters and if there are check if the character is not actually the '$' sign.

 private String normalizeDiscountCode(String discountCode) {
    for(char c : discountCode.toCharArray()) {
      if(!Character.isLetter(c) &&  c != '$' ){
        throw new IllegalArgumentException("Invalid discount code");
      }
    }
    return discountCode.toUpperCase();
  }