我的代碼的工作方式也是我想要的,但它使用了很多行。在我的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