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 trialXuanzheng Lin
2,466 PointsFailed 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.
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
Steve Hunter
57,712 PointsHi 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.