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

I'm having trouble checking for the '$' symbol in a string

I can figure out how to check for letters, and then throw an exception, but i dont know how to check for the '$' symbol in the string.

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;
  }

  private String normalizeDiscountCode(String discountCode){
     discountCode=discountCode.toUpperCase();
    char symbol='$';
    for(int i=0;i<discountCode.length();i++){
      if(!Character.isLetter(discountCode.charAt(i))||discountCode.indexOf(i)!=symbol){
        throw new IllegalArgumentException("a letter, or a $ symbol, is required");
      }
    }


    return discountCode;
  }

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

2 Answers

I figured it out, my logic was incorrect. It should have been checking for both letters and the symbol, not either or.

Hi Zack,

Glad you got that sorted; sorry not to get back to you last night.

Did you figure out a cleaner way of managing the loop? You've gone down the local counter variable route but a for:in loop is a little cleaner.

That would look like:

for(char letter : discountCode.toCharArray()){

}

This does the same as your loop; it iterates over `discountCode one char at a time, storing each char in turn within the letter variable. But it doesn't require a counter variable or any incrementing. Once you've got that set up you can do the tests:

  for(char letter : discountCode.toCharArray()){
    if(! Character.isLetter(letter) && letter != '$'){
      throw new IllegalArgumentException("Informative error message");
    }
  }

Putting all that together gives you the whole method:

private String normalizeDiscountCode(String discountCode){
  for(char letter : discountCode.toCharArray()){
    if(! Character.isLetter(letter) && letter != '$'){
      throw new IllegalArgumentException("Informative error message");
    }
  }
  return discountCode.toUpperCase();
}

I hope that helps,

Steve.