Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使adjustQuantity方法停止在0_Java - Fatal编程技术网

Java 使adjustQuantity方法停止在0

Java 使adjustQuantity方法停止在0,java,Java,我正在为我的Java简介类做一个项目,我们必须格式化一个 +adjustQuantity(adjustingQuantity:int):void // Adjusts the book stored quantity by the given amount. The final // must be >= 0

我正在为我的Java简介类做一个项目,我们必须格式化一个

+adjustQuantity(adjustingQuantity:int):void // Adjusts the book stored quantity by the given amount. The final
                                                                                       //    must be >= 0
我已经有了添加调整间隔的代码

public void adjustQuantity(int adjustingQuantity)
    { 
        int iAdjustingQuantity;
        int iQuantity= this.quantity;
        int iNewQuantity = (this.quantity + iAdjustingQuantity);
        if(iNewQuantity <=0)

    }
public void adjustmentquantity(整数调整数量)
{ 
国际贸易量;
int IQUANTY=此数量;
int iNewQuantity=(this.quantity+iAdjustingQuantity);

如果(iNewQuantity您可以在另一时间分配变量:

public void adjustQuantity(int adjustingQuantity)
    { 
        int iAdjustingQuantity;
        int iQuantity= this.quantity;
        int iNewQuantity = (this.quantity + iAdjustingQuantity);
        if(iNewQuantity <=0)
            iNewQuantity = 0;

        this.quantity=iNewQuantity;
    }
public void adjustmentquantity(整数调整数量)
{ 
国际贸易量;
int IQUANTY=此数量;
int iNewQuantity=(this.quantity+iAdjustingQuantity);
如果(数量可能是这个

public void adjustQuantity(int adjustingQuantity) { 
    int iNewQuantity = this.quantity + adjustingQuantity;
    if (iNewQuantity >= 0)
        this.quantity = iNewQuantity 
    else
        this.quantity = 0;
}
根据以上内容,您可以保证仅当新数量为零或正时,数量才会调整,否则我们将分配零。

如果((调整数量+此.quantity)<0)
if ((adjustingQuantity+this.quantity) < 0)
  throw new Exception("adjustingQuantity must be greater than or equal to zero");
抛出新异常(“调整数量必须大于或等于零”);
基本操作应为:

this.iQuantity = Math.max(iQuantity + iAdjustingQuantity, 0);
但是,没有理由在整型变量上使用
i
前缀;您的方法应该足够短,不需要前缀。此外,假设您的需求发生变化,并且您必须切换到
long
s。您是否只需更改类型并拥有:

long iQuantity;
现在,如果新值为负值,您希望发生什么?是否要将其设置为零?是否要引发异常?是否要还原?这取决于您的决定

@jcalfee314建议抛出一个
异常
;我建议使用
异常
的一个特定子类。
索引自动边界异常
似乎不太正确;我会使用
IllegalArgumentException


在大型程序中使用此功能的最佳方法可能是使用
PropertyChangeEvent
PropertyChangeListener
VetoableChangeListener
。查阅JavaBeans规范,第7.4节。使
iQuantity
绑定和约束。

效果很好。谢谢!(我会向您竖起大拇指,但我没有足够的代表这么做,对不起。)通常,您会想知道调整是否失败。由于返回值为null,将使用异常。减少变量数量或更正iAdjustingQuantity的用法(iAdjustingQuantity未初始化)。