gpt4 book ai didi

Java : If statement to process amount you want whilst discarding the rest?

转载 作者:行者123 更新时间:2023-11-30 03:36:55 25 4
gpt4 key购买 nike

我有以下脚本:

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 这样的数字,它仍然会打印消息“此存储盒已达到其最大值...” 不添加任何内容。在这种情况下,我将如何编辑脚本以添加到框中直到最大容量,并丢弃多余的量。谢谢。

最佳答案

这是一个解决方案:

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");
}

注释:

  • 留给读者的练习:警告浪费的奶酪数量!
  • 命名约定:Java 使用驼峰命名法;最好是 addCheesecheeseAmount 等。

关于Java : If statement to process amount you want whilst discarding the rest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com