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

Xuanzheng Lin
Xuanzheng Lin
2,466 Points

Failed in Task 1 when I am in Task 2

The instruction of task 2 is "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." However, i cannot pass task 2 because it says task 1 is failing lol.

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

  // class code omitted for brevity

  public void applyDiscountCode(String discountCode){
    String want = normalizeDiscountCode(discountCode);
    this.discountCode = want;
    /*try {
      String want = normalizeDiscountCode(discountCode);
      this.discountCode = want;
    } catch (IllegalArgumentException iae) {
      System.out.print(iae.getMessage());
    }*/
  }

  private String normalizeDiscountCode (String discountCode) {
    String upper = "";
    for (char letter : discountCode.toCharArray()) {
      if (! Character.isLetter(letter) || letter != '$') {
        throw new IllegalArgumentException("Invalid discount code.");
      } else if (Character.isLetter(letter)) {
        upper += Character.toUpperCase(letter);
      } else {
        upper += letter;
      }
    }
    return upper;
  }
}

1 Answer

Hi there,

I think there's another thread on this challenge where there's a suggested solution.

Here, you've done a similar test using || rather than && and then have uppercased each letter in turn and reassembled the word one character at a time. There's no need to do that. The if statement filters out invalid codes and throws an error.

If that doesn't happen, just return the original discountCode parameter chained to .toUpperCase().

Steve.