[英]limit the number of times a method can be called in Java
如何限制可以調用 addAddition() 的次數? 例如,如果我想將其限制為 4 次,那么在我在 Main class 中調用它 4 次后,會出現一條錯誤消息。
public class BaseBurger {
public void addAddition(int additionNumber) {
switch (additionNumber) {
case 1:
System.out.println("Bacon added!");
this.price += 3;
i++;
break;
case 2:
System.out.println("Salad added!");
this.price += 2.5;
i++;
break;
case 3:
System.out.println("Juice added!");
this.price += 3;
i++;
break;
case 4:
System.out.println("Sauce added!");
this.price += 3.5;
i++;
break;
default:
System.out.println("Invalid value!");
}
}
}
添加一個字段來計算您的方法被調用的次數。 一旦達到最大限制,拋出你的錯誤。 因此,您的代碼可以...
public class BaseBurger {
private int counter = 0;
public void addAddition(int additionNumber) {
if (counter == 4) throw new CUSTOM_ERROR();
counter++; // increase counter each time.
switch (additionNumber) {
case 1:
System.out.println("Bacon added!");
this.price += 3;
i++;
break;
case 2:
System.out.println("Salad added!");
this.price += 2.5;
i++;
break;
case 3:
System.out.println("Juice added!");
this.price += 3;
i++;
break;
case 4:
System.out.println("Sauce added!");
this.price += 3.5;
i++;
break;
default:
System.out.println("Invalid value!");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.