我有以下脚本:
public void addcheese(int addcheese) {
if (cheeseamount + addcheese < mincapacity) {
System.out.println("Sorry no more cheese can be removed.");
} else if (cheeseamount + addcheese <= maxcapacity) {
if ((cheeseamount + addcheese > 1900) && (cheeseamount + addcheese < 2000)) {
System.out.println("Warning : The box is nearing it's maximum capacity.");
}
cheeseamount = cheeseamount + addcheese;
}
else {
System.out.println("This storage box has reached its maximum capacity. You cannot fill it any more");
}
}
(注意:在构造函数maxcapacity = 2000中)
脚本可以正常工作,但是有一个问题,如果我输入一个像3400这样的数字,它仍然会打印消息&#34;这个存储盒已达到最大值... &#34; ,不添加任何内容。如何编辑脚本,在这种情况下,添加到框中直到maxcapacity,并丢弃多余的金额。谢谢。
答案 0 :(得分:2)
这是一个解决方案:
public void addcheese(int addcheese)
{
final int target = cheeseamount + addcheese;
if (target < mincapacity) {
System.out.println("Sorry, no cheese can be removed");
return;
}
if (target >= maxcapacity) {
cheeseamount = maxcapacity;
System.out.println("Box is full");
return;
}
cheeseamount = target;
if (cheeseamount > 1900)
System.out.println("Warning, box is nearing its maximum capacity");
}
注意:
addCheese
,cheeseAmount
等。答案 1 :(得分:0)
使用此条件添加另一个if else:
else if (cheeseamount != maxcapacity && cheeseamount + addcheese > maxcapacity) {
cheeseamount = maxcapacity;
System.out.println("Warning : The box just reached it's maximum capacity.");
}
答案 2 :(得分:0)
实现此目的的一种方法是修改您的else语句。在else语句中,您可以简单地将奶酪的数量设置为最大量,基本上添加尽可能多的奶酪并丢弃其余的奶酪:
else {
cheeseamount = 2000;
System.out.println("This storage box has now reached its maximum capacity.");
}
然而,在这里你丢失了丢弃的奶酪量。如果你想保留这个数字,你可以创建一个新的变量:
else {
int extraCheese = cheeseamount + addcheese - 2000;
cheeseamount = 2000;
System.out.println("This storage box has now reached its maximum capacity.");
}
附注:将最大容量和任何其他幻数保存为常数是个好主意。魔术数字基本上是随机数字,出现在整个代码中,其他任何查看代码的人都无法理解。通过创建具有描述性名称的常量,您可以向其他程序员清楚地表明该数字代表什么,您也可以在将来轻松修改它。