【问题标题】:Codename One: How to calculate a running total for each button iteration?代号一:如何计算每个按钮迭代的运行总数?
【发布时间】:2016-04-23 01:20:32
【问题描述】:

我想计算每次按下按钮时的总和。它应该加一个数量加上总数量(如果按钮已经被按下)。以下是我的代码sn-p。

TextField quantity = new TextField("", "Volume of water (ml)", 4, TextArea.ANY);
intake.addComponent(quantity);

Button add = new Button("Add");
intake.addComponent(add);

...

int total = 0;

//--------------------------------------------------------------
add.addActionListener((ActionEvent ev) -> {
Storage s = Storage.getInstance();

try {

    String num = quantity.getText();
    Integer num2 = Integer.parseInt(num);

    String name = itemName.getText();

    total += num2;
    Dialog.show("", "You have consumed a total of " + Integer.toString(total) + "ml of water", "OK", "Close");

... 

} catch {
    ... 
}

});

使用上面的代码,下面的代码 sn-p 会出现错误(“从 lambda 表达式引用的局部变量必须是最终的或有效的最终”)。我也尝试过使用“public void actionPerformed()”方法,但没有成功

total += num2;
Dialog.show("", "You have consumed a total of " + Integer.toString(total) + "ml of water", "OK", "Close");

因此,我将不胜感激有关如何编写运行总计代码的任何帮助和指导。

【问题讨论】:

    标签: codenameone cumulative-sum


    【解决方案1】:

    您可以使用一种方法作为替代方法,例如将调用的 increaseTotal,而不是直接操作总变量。正如 Shai 提到的事件不能并行发生,所以不需要添加同步标签或其他。

    public void increaseTotal(int addedValue){
         this.total += addedValue;
    }
    

    【讨论】:

      【解决方案2】:

      total 成为您班级的成员。由于 lambda(事件调用)可能并行发生,因此从 lambda 内部更改总数可能会产生非法状态(从技术上讲,事件不能并行发生,但 Java 编译器不知道这一点并且不允许非最终访问)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-16
        • 2016-08-31
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 2022-11-18
        相关资源
        最近更新 更多