且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单击 JCheckBox 时添加值

更新时间:2023-12-03 17:28:34

您的第一个问题(您可能注意到也可能没有注意到)是您的 JCheckBoxes 数组仅包含空元素:

Your first problem (which you may or may not have noticed) is your array of JCheckBoxes only contains null elements:

// check boxes are null here
private JCheckBox americano, espresso, doubleEspresso, latte;

// array created with only null elements
JCheckBox[] boxes = new JCheckBox[]{americano, espresso, doubleEspresso, latte};

所以你需要在实例化实际复选框之后创建数组.

So you need to create the array after instantiating the actual check boxes.

...

americano = new JCheckBox("Americano", false);
checkPanel.add(americano);
americano.addActionListener(this);

espresso = new JCheckBox("Espresso", false);
checkPanel.add(espresso);
espresso.addActionListener(this);

doubleEspresso = new JCheckBox("Double Espresso", false);
checkPanel.add(doubleEspresso);
doubleEspresso.addActionListener(this);

latte = new JCheckBox("Latte", false);
checkPanel.add(latte);

boxes = new JCheckBox[] {
    americano, espresso, doubleEspresso, latte
};

然后作业建议使用数组,因为您可以创建另一个平行的价格数组(您已经这样做了).但是由于您需要并行使用这些价格,因此您不能使用 for each 循环.你需要索引.然后,每次选择或取消选择任何内容时,您都需要重新计算整个成本.

Then the assignment is suggesting to use arrays because you can create another parallel array of prices (which you did). But since you need these prices in parallel you cannot use a for each loop. You need the index. Then you need to recalculate the entire cost every time anything is selected or deselected.

final double[] prices = {
    3.75, 4.00, 4.50, 3.50
};

...

double total = 0.0;

for(int i = 0; i < boxes.length; i++) {
    if(boxes[i].isSelected()) {
        total += prices[i];
    }
}

还有另外两个注释似乎超出了作业的范围:

There's two other notes that seem to be outside the scope of the assignment:

  • 您应该始终为这种关联创建一个类.
  • 你不应该使用 double 来赚钱.使用 BigDecimal 或类似的东西.
  • You should always make a class for this kind of association.
  • You should never use double for money. Use BigDecimal or something like it.

使用类使逻辑更简单,不使用 double 使得该小数加法的计算不会产生错误.

Using a class makes logic simpler and not using double makes the calculation not incur error for this decimal addition.

class PricePair {
    JCheckBox jCheckBox;
    BigDecimal price;
}

BigDecimal total = new BigDecimal("0.00");

for(PricePair option : options) {
    if(option.jCheckBox.isSelected()) {
        total = total.add(option.price);
    }
}