在normalizeDiscountCode中,验证仅使用字母或$字符。如果使用了其他任何字符,则抛出IllegalArgumentException并显示消息Invalid Discount Code。
我尝试过
char[] chars = code.toCharArray();
if (! Character.isLetter(chars.length) || code != "$"){
//if (code.matches("[a-zA-Z$]")){
throw new IllegalArgumentException("Invalid discount code");
}
this.discountCode = code.toUpperCase();
return code.toUpperCase();
}
还有这个
if (! Character.isLetter(code.length()) || code != "$"){
throw new IllegalArgumentException("Invalid discount code");
}
this.discountCode = code.toUpperCase();
return code.toUpperCase();
}
public class Order {
private String itemName;
private int priceInCents;
private String discountCode;
private String normalizeDiscountCode(String code){
//char[] chars = code.toCharArray();
if (! Character.isLetter(code.length()) || code != "$"){
//if (code.matches("[a-zA-Z$]")){
throw new IllegalArgumentException("Invalid discount code");
}
this.discountCode = code.toUpperCase();
return code.toUpperCase();
}
public Order(String itemName, int priceInCents) {
this.itemName = itemName;
this.priceInCents = priceInCents;
}
public String getItemName() {
return itemName;
}
public int getPriceInCents() {
return priceInCents;
}
public String getDiscountCode() {
return discountCode;
}
public void applyDiscountCode(String discountCode) {
this.discountCode = discountCode;
this.discountCode = normalizeDiscountCode(discountCode);
}
}
public class Order {
private String itemName;
private int priceInCents;
private String discountCode;
private String normalizeDiscountCode(String code){
//char[] chars = code.toCharArray();
if (! Character.isLetter(code.length()) || code != "$"){
//if (code.matches("[a-zA-Z$]")){
throw new IllegalArgumentException("Invalid discount code");
}
this.discountCode = code.toUpperCase();
return code.toUpperCase();
}
public Order(String itemName, int priceInCents) {
this.itemName = itemName;
this.priceInCents = priceInCents;
}
public String getItemName() {
return itemName;
}
public int getPriceInCents() {
return priceInCents;
}
public String getDiscountCode() {
return discountCode;
}
public void applyDiscountCode(String discountCode) {
this.discountCode = discountCode;
this.discountCode = normalizeDiscountCode(discountCode);
}
}
答案 0 :(得分:1)
需要使用foreach循环,这是我一直努力解决的问题。我很难弄清楚如何将完整的Strings转换为char。
private String normalizeDiscountCode(String code){
for (int i = 0; i < code.length(); i++){
char c = code.charAt(i);
if (! Character.isLetter(c) && c != '$'){
throw new IllegalArgumentException("Invalid discount code");
}
}
this.discountCode = code.toUpperCase();
return code.toUpperCase();
}