Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Delivering the MVP Applying a Discount Code

Code for finding if String contains only letters and $ character..??

  private String normalizeDiscountCode(String discountCode){
    if( discountCode != "[a-zA-z]" || char!= '$'){
      throw new IllegalArgumentException("Invalid Discount Code");
    }

1 Answer

Hi Atul,

You need to break the parameter that is passed in into a char array and iterate over each char in turn. There, test to see if the character is a letter (Use the class method isLetter()). Also test if the character is a dollar sign. It is better to test whether the character is not a letter and not a dollar sign. Use the not operator, !.

So, set up a for loop and break the discountCode (or whatever you called your parameter) down to an array using toCharArray(). Then do the test, !Character.isLetter(c) where c is your loop local variable && also c != '$'. If that evaluates to true, throw the IllegalArgumentException, else return the upper case discountCode and exit the method. That all looks like:

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

This post Goes into a little more detail of this, should you need it.

Steve.