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


3,419 Points

Applying a discount code challenge

Question: is there any easier/shorter way to do below task?

Task: 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.

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

1 Answer

james south
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

you can consolidate your loop a little. instead of using an integer loop up to the length of the discount code to test chars with charAt, you could use an enhanced for loop of the chars in discount code directly, for (char ch : discount code.toCharArray()) .