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

I want to accept as input only English alphabetic letters and dollar symbol... How can I write code for this condition

I have a trouble writing 'to accept dollar as input'.

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

  private String normalizeDiscountCode(String discountCode){
    if(!String.isLetter(discountCode) || !String.equals('$')){
      throw new IllegalArgumentException("Invalid discount code");
    }

    discountCode =   discountCode.toUpperCase();
    return discountCode;
  }



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



  public String getItemName() {
    return itemName;
  }

  public int getPriceInCents() {
    return priceInCents;
  }

  public String getDiscountCode() {
    return discountCode;
  }

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

  }
}

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

It's a bit of an advanced topic, and treehouse has a course on it, but this is an ideal problem to solve with regular expressions

Thank you very much :)

But I'm unable to find solution for this question..

Samuel Ferree
Samuel Ferree
31,722 Points

Oh sorry, I didn't see that that this question was part of a challenge.

the isLetter method is a member of Character, not String, so you'll need to loop through each character in the discount code to check instead of checking on the string as a whole.

  private String normalizeDiscountCode(String discountCode) {
    for(int i = 0; i < discountCode.length(); i++) {
      char ch = discountCode.charAt(i);
      if(!(Character.isLetter(ch) || ch == '$')) { // if character is not a letter or '$'
        throw new IllegalArgumentException();
      }
    }
    return discountCode.toUpperCase();
  }