如何从两个Jtext字段计算数字



我正在设计一个订餐系统,我需要得到顾客支付的现金输入,然后减去他们需要支付的总价来计算零钱。我的JTextField无法显示更改的正确答案,它只显示0.0。我不确定我的代码出了什么问题。希望你们都能帮助我。感谢你们的帮助,谢谢!

public Cash() {
init();
btnPay.addActionListener(this);
setVisible(true);
}
public String returnChange1() {
double change = 0.00 ;
double custPay;
String total = lblDisplayTotal.getText();
double a=Double.parseDouble(total);
if (!(txtCustPay.getText().isEmpty())){
custPay = Double.parseDouble(txtCustPay.getText());
change = custPay - a;
}
return String.valueOf(change);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btnPay)) {
returnChange1();
}
}
public void init() {
txtChange = new JTextField(returnChange1());
txtChange.setSize(150, 30);
txtChange.setLocation(150, 250);
add(txtChange);
}

您没有将函数分配给文本字段。在按钮操作中,不要简单地调用函数,在这种情况下,你应该做的是将函数分配给文本字段:txtChange.setText(returnChange1()),也试着在将文本转换为双精度的地方放一个try-and-catch:

try{
double a = Double.parseDouble(total);
}catch(NumberFormatException e){
e.printStackTrace;
}

当用户错误地输入非数字字符时,上述代码非常有用。

public Cash() {

init();
btnPay.addActionListener(this);
setVisible(true);
}
public String returnChange1() {
double change = 0.00;
double custPay;
String total = lblDisplayTotal.getText();
double a = Double.parseDouble(total);
if (!(txtCustPay.getText().isEmpty())) {
custPay = Double.parseDouble(txtCustPay.getText());
change = custPay - a;
}
return String.valueOf(change);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btnPay)) {
txtChange.setText(returnChange1());
}
}
public void init() {
txtChange = new JTextField(returnChange1());
txtChange.setSize(150, 30);
txtChange.setLocation(150, 250);
add(txtChange);
}

最新更新