有没有人在加油站或杂货店使用过这些机器,在那里你可以通过捐赠可回收物品获得资金?好吧,我想制作一个虚拟的,到目前为止一切都很好,直到我不得不做一些数学运算。我只有 13 岁,所以这部分非常棘手,尽管我认为它会很简单。我需要可回收类型的价值乘以金额,然后添加到总金额中。但是,它似乎只是将总数更改为我最近添加的值,而不是将其添加到总金额中。假设我添加了 2 罐,即 10 美分,然后我再添加一罐,而不是总共 15 美分,我只有 5 美分。希望你明白。我还想对我的代码提出一些建设性的批评。我知道这不是最好的,但我刚开始学习 java,所以任何帮助都会很可爱。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Machine {
static JLabel label;
static JComboBox typeList;
static JComboBox amountList;
public static void GUI(){
JFrame frame = new JFrame("Recyclables Machine");
frame.setVisible(true);
frame.setSize(300,125);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
Integer[] amounts = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
amountList = new JComboBox(amounts);
panel.add(amountList);
String[] types = {"Choose Recycable Type","Plastic Bottle","Can","2 Liter","Glass Bottle"};
typeList = new JComboBox(types);
panel.add(typeList);
JButton button = new JButton("Add");
panel.add(button);
label = new JLabel("Total Money: 0 cents");
panel.add(label);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gettinItDone();
}
});
}
public static void gettinItDone(){
String type = (String)typeList.getSelectedItem();
int amount = (int)amountList.getSelectedItem();
int money = 0;
int temp = 0;
if(type.equals("Plastic Bottle")){
temp = 5 * amount;
money = temp + money;
label.setText("Total Money: "+ money +" cents");
}else{
if(type.equals("Can")){
temp = 5 * amount;
money = temp + money;
label.setText("Total Money: "+ money +" cents");
}else{
if(type.equals("2 Liter")){
temp = 10 * amount;
money = temp + money;
label.setText("Total Money: "+ money +" cents");
}else{
if(type.equals("Glass Bottle")){
temp = 10 * amount;
money = temp + money;
label.setText("Total Money: "+ money +" cents");
}else{
JOptionPane.showMessageDialog(null,"Invalid Recyclable Type", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}