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 trialAhmed Sadat
Java Web Development Techdegree Student 643 PointsHi guys this is example don't get any error in my IDE but get error in Treehouse ...what is the problem
there's error in this practice but when i copy the code to my IDE there's no problem ?!..what is the problem ??
public class Order {
private String itemName;
private int priceInCents;
private String discountCode;
private String normalizeDiscountCode(String discountCode){
if(!discountCode.matches("^[a-zA-Z_]+"))
{
throw new IllegalArgumentException("invalid discount code");
}
return discountCode.toUpperCase() ;
}
public Order(String itemName, int priceInCents) {
this.itemName = itemName;
this.priceInCents = priceInCents;
}
// snip
public void applyDiscountCode(String discountCode) {
try{
this.discountCode = normalizeDiscountCode( discountCode);
}catch(IllegalArgumentException iae){
System.out.println(iae.getMessage()) ;
}
}
}
2 Answers
Steve Hunter
57,712 PointsHi there,
I approached this without using the regexp.
In the method, create a for
loop to iterate over the received discount code. Test whether each letter in the code, in turn, is a letter or a '$'. If it isn't, throw the exception, if it is, do nothing. If you reach the end of the loop without the exception being thrown, return the upper case discount code.
Careful with your logic as you need to identify scenarios where the letter is not a, erm, letter and also not a dollar sign.
I hope that helps.
Steve.
andren
28,558 PointsAs Steve mentions the intended solution to this exercise is to use a for
loop, since regex has not really been taught in this course. However you can certainly use regex, and your code is actually quite close.
The issue is that your regex tests for letters and the _ character, while the challenge is to test for letters and the $ character.
So if you simply change your regex to this: "^[a-zA-Z$]+" then your code would work fine.