简体   繁体   English

Java-调用方法时加在一起

[英]Java - Add together amount when method is called

this might seem daft but I just can't seem to figure this out. 这似乎很愚蠢,但我似乎无法弄清楚。 Ok so I'm new to programming and I've hit a snag when it comes to doubling an amount by itself. 好的,所以我是编程新手,在将自身数量加倍时,我遇到了麻烦。

I'm calling a method from another object class which gives the total price of wine selected from a customer. 我正在从另一个对象类中调用一个方法,该方法给出了从客户选择的葡萄酒的总价。

ie - winecase.getPrice(); 即-winecase.getPrice();

Within the class website (the class im calling the external method from) theres a field called salesTotal which adds the amount of revenue generated from the website. 在类网站中(类从其调用外部方法),存在一个名为salesTotal的字段,该字段可添加从网站生成的收入金额。 The above method is being called from within the checkout method of the website class (if that makes sense). 从网站类的checkout方法中调用上述方法(如果有意义)。

I basically want the field to store the value of the getPrice each time the checkout method is called... for example if the case of wine was £30, I want it to be £30 when the method is first called but then £60 the second time £90 the next etc (so effectively doubling itself). 我基本上希望每次调用结帐方法时该字段都存储getPrice的值...例如,如果酒的价格为30英镑,则我希望在第一次调用该方法时为30英镑,但随后为60英镑第二次第二次£90(如此有效地使自己翻倍)。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You could try using a setter, ie 您可以尝试使用二传手,即

 BigDecimal salesTotal;

 public BigDecimal getSalesTotal() {
      return salesTotal;
 }

 public void setSalesTotal(BigDecimal salesTotal) {
      this.salesTotal = salesTotal;
 }

and then call 然后打电话

setSalesTotal(this.getSalesTotal() + winecase.getPrice());

or encapsulate this logic in a separate method which will receive an amount of money that has to be added to total as a parameter like this: 或将此逻辑封装在一个单独的方法中,该方法将获得一定数量的钱,这些钱必须像这样的参数加到total中:

calculateSalesTotal(BigDecimal amountToAdd) {
    this.setSalesTotal(this.getSalesTotal() + amountToAdd);
}

and then call it calculateSalesTotal(winecase.getPrice()); 然后将其命名为calculateSalesTotal(winecase.getPrice());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM