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 Validating and Normalizing User Input

Maan Azzam
Maan Azzam
2,239 Points

Challenge problems.

Can someone tell me if what i wrote can work (with some modifications) or should i just use

for (char letter: discountCode.charArray()) 

first to change the String into char.

Challenge question #2 : 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.

My "wrong" Answer :

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

  }

  private String normalizeDiscountCode(String discountCode) {
    if(!Character.isLetter(discountCode.charAt(0)) || !discountCode.contains("$")  ) {
      throw new IllegalArgumentException("Invalid discount code");
    }    
    return this.discountCode = discountCode.toUpperCase();
  }

Please keep in mind that i dont get Compiler errors. just that i dont pass the challenge.

1 Answer

Jialong Zhang
Jialong Zhang
9,821 Points

I think there is a logic problem this line. for the second part, if a string does not contain $, it will throw a IllegalArgumentException. Giving string "Hello", it will also throw IllegalArgumentException because this string does not contain $.

if(!Character.isLetter(discountCode.charAt(0)) ||  !discountCode.contains("$")  ) { // logic error , however, change || to && will not fix the problem.

// I don't know if this challenge only needs to check first character or all character.

//my solution is something like 

     public String normalizeDiscountCode(String discountCode) {
        for(int i =0; i< discountCode.length(); i++){
             if(!Character.isLetter(discountCode.charAt(i)) && !discountCode.substring(i,i+1).equals("$") ) {
                  throw new IllegalArgumentException("Invalid discount code");
                }    
             this.discountCode = discountCode.toUpperCase();
              }

            return discountCode;
        }