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

Przemyslaw Mazur
PLUS
Przemyslaw Mazur
Courses Plus Student 9,296 Points

Task one is no longer passing. Please help.

It was fine before and I see no error. What do you think?

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

  private String normalizeDiscountCode(String code) {

    for(int i=0; i<code.length();i++) {
     char x = code.charAt(i);
     if(!(Character.isLetter(x)) || x != '$') {
      throw new IllegalArgumentException("Invalid discount code");
     }
    } 
    code = code.toUpperCase();    
   return code;
  }

  // snip

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

3 Answers

Hi there,

Think through your logic. You want to throw the exception if the character is not a letter AND is not a '$'.

Using OR would throw the exception if the character was a '$' as it is not a letter.

I hope that makes sense.

Steve.

Simon Coates
Simon Coates
28,694 Points

try

    private String normalizeDiscountCode(String code) {       
      for(int i=0; i<code.length();i++)       {
       char x = code.charAt(i);
       if(!Character.isLetter(x) && x != '$')      {
        throw new IllegalArgumentException("Invalid discount code");
       }
      }   
      return  code.toUpperCase();  
    }

I think you forgot to apply de morgan's law. If character can be a letter OR '$', then the error condition is when it isn't a character AND isn't '$'.

An alternative is keeping things simple with:

    private String normalizeDiscountCode(String code) {

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

     if(! (Character.isLetter(letter) || letter == '$')) {
      throw new IllegalArgumentException("Invalid discount code");
     }
    } 
    return code.toUpperCase();
  }
Przemyslaw Mazur
PLUS
Przemyslaw Mazur
Courses Plus Student 9,296 Points

Yup I see now. The hole in my logic is now patched. Thanks guys.

No problem! :+1: Glad you got going again.