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 trialAbhilasha jangid
2,925 Pointsis here I use for loop for string discount convert int to letter!!
how I say condition for $ sign
public class Order {
private String itemName;
private int priceInCents;
private String discountCode;
private String normalizeDiscountCode(String discountCode){
if(! Character.isLetter(discountCode) || discountCode == '$' ){
throw new IllegalArgumentException (" Invalid discount code");
}
return discountCode.toUpperCase();
}
public Order(String itemName, int priceInCents) {
this.itemName = itemName;
this.priceInCents = priceInCents;
}
public void applyDiscountCode(String discountCode) {
this.discountCode = normalizeDiscountCode(discountCode);
}
}
1 Answer
Steve Hunter
57,712 PointsHi there,
Yes, you need a for
loop here. That will give you access to each character in the code so you test it to see if it is a letter or a '$'. You can't test the whole string at the same time, unfortunately!
So, start by converting the string to an array of chars. Use the .toCharArray()
method with dot notation on the discountCode
. You need to create a new variable to hold each character in turn, it is of type char
and I called it letter
for obvious reasons!
Once you've done this, you can test letter
in a similar way as you've already suggested. Have a think about what you're trying to achieve. Careful with ||
and &&
as well as ==
and !=
.
Here's the start of the loop - I'll leave you to figure out the rest but do shout if you get stuck:
for (char letter : discountCode.toCharArray()){
// test 'letter' in here
}
Steve.