我的代码的工作方式也是我想要的,但它使用了很多行。在我的Java代码中更好地使用for循环
它关于一个食品订单终端和我告诉你的部分是关于从购物车中删除 JButtons。
我不想编辑每一个在Arraylist中的JButton。我认为一个循环可以帮助在这里,但我不知道如何做到这一点。
素不相识
public class Bestellterminal {
private int x = 0;
private double Preis = 0;
private double classicpreis = 2.5;
private ArrayList<JButton> classiciconlist = new ArrayList<JButton>();
public void addComponentsToPane2(final Container pane) {
for(int i = 0; i <= 50; i++) {
classiciconlist.get(i).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (x == 0) {
Preis = Preis - classicpreis;
Locale currentlocale = Locale.GERMANY;
NumberFormat numberFormatter =
NumberFormat.getCurrencyInstance(currentlocale);
String classicpreisx = numberFormatter.format(classicpreis);
String preisx = numberFormatter.format(Preis);
labelsumme.setText(String.valueOf("Summe: " + preisx));
classiciconlist.get(1).setVisible(false);
x++;
}
else if (x == 1) {
Preis = Preis - classicpreis;
Locale currentlocale = Locale.GERMANY;
NumberFormat numberFormatter =
NumberFormat.getCurrencyInstance(currentlocale);
String classicpreisx = numberFormatter.format(classicpreis);
String preisx = numberFormatter.format(Preis);
labelsumme.setText(String.valueOf("Summe: " + preisx));
classiciconlist.get(2).setVisible(false);
x++;
}
else if (x == 2) {
Preis = Preis - classicpreis;
Locale currentlocale = Locale.GERMANY;
NumberFormat numberFormatter =
NumberFormat.getCurrencyInstance(currentlocale);
String classicpreisx = numberFormatter.format(classicpreis);
String preisx = numberFormatter.format(Preis);
labelsumme.setText(String.valueOf("Summe: " + preisx));
classiciconlist.get(3).setVisible(false);
x++;
}
}});
}
}
}
是否有这三个条件有什么区别?任何三条条款都完全相同的条款完全可以脱离条件。 – David
这可能更适合codereview.stackexchange.com,虽然我会检查的第一件事是那些if-elseif块。它们似乎是相同的,只是使用了列表索引并且可以计算为'x + 1'(您需要对x进行范围检查,例如0 <= x
Thomas
重复太多。需要干燥。只有差异是x值和列表中的索引。 – duffymo