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

Jennifer Barbee
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Barbee
Front End Web Development Techdegree Student 2,387 Points

How do I verify that only letters or the '$' sign is being used, and to throw an exception if other characters are used

Hello,

I'm having trouble getting this code to run properly. Can anyone help explain what I'm doing wrong, and break it down for me a little bit? I appreciate your guy's help!

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(applyDiscountCode() { 
    for (char letter : discountCode.toCharArray()) {
      if(! Character.isLetter(letter) && letter !='$') {
        throw new IllegalArgumentException("Invalid discount code");
         }
       return discountCode;
       }

   }
}
Jennifer Barbee
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Barbee
Front End Web Development Techdegree Student 2,387 Points

Here is the code challenge:

Challenge Task 2 of 2

Now let's use your validation skills. Only letters and the $ symbols are allowed in the discount code. Check Example.java for use cases

In the normalizeDiscountCode verify that only letters or the $ character are used. If any other character is used, throw a IllegalArgumentException with the message Invalid discount code.

1 Answer

Hi Jennifer,

There's a couple of points in here but most of your code is absolutely correct. :+1:

First, pass in a String into the normalize method; don't call the other method. Just pass in a String call it discountCode. You then use that inside your method, as you have done.

Second, your return misses the .toUpperCase() method out - add that back on.

Also, you are making the return call inside the for loop. Make sure it is outside of if. I think you just need to move it down one line, beyond one of the curly braces.

I think that's it - let me know how you get on.

Steve.

Glad you got it sorted! :+1: :smile: