gpt4 book ai didi

java - 数学 "equations"无法正常工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:56 24 4
gpt4 key购买 nike

有没有人在加油站或杂货店使用过这些机器,在那里您可以通过捐赠可回收元素来赚钱?好吧,我想制作一个虚拟的,到目前为止一切都很好,直到我不得不做一些数学运算。我只有 13 岁,所以这部分非常棘手,尽管我认为它会很简单。我需要将可回收类型的值(value)乘以数量,然后加到总金额中。但不是将它添加到总金额中,它似乎只是将总金额更改为我最近添加的值。假设我加了 2 jar ,即 10 美分,然后我又加了一 jar ,而不是总共 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);
}
}
}
}
}
}

最佳答案

“money”变量的范围仅在事件监听器触发时有效。

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gettinItDone();
}
});

您需要将资金存储在#getIniitDone 方法的范围之外。

关于java - 数学 "equations"无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com