Java变更计算

时间:2013-01-03 09:55:12

标签: java

我有一个更改算法计算,它加起来而不是减去用户支付的金额。我希望程序能够使用一组货币按钮从文本框中扣除支付金额,当金额超过支付时,余额应返回给用户。每次我使用消息框点击任何货币按钮时,它会相加。感谢

这些是货币按钮:

      private void tenPoundButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    // TODO add your handling code here:
    amountToPay -= 1000;
    calculate(amountToPay);
}                                              

private void twentyPoundButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    // TODO add your handling code here:
    amountToPay -= 2000;
    calculate(amountToPay);
}                                                 

private void fiftyPoundButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    // TODO add your handling code here:
    amountToPay -= 5000;
    calculate(amountToPay);
}         

这是改变算法:

    public void calculate(double amount) {

    if (amount > 0) {
        amountPaidTextBox.setText(pounds.format(amount/100));
    }
    else {
        amountPaidTextBox.setText("");

        if (amount < 0){
            double change;
            change = -amount;

            javax.swing.JOptionPane.showMessageDialog(this, "Your change is " + pounds.format(change / 100)

                    + coins (change), 
                    "change", JOptionPane.INFORMATION_MESSAGE);
        }
        else {
            javax.swing.JOptionPane.showMessageDialog(this, "Thank you, Exact Amount");
        }
    }
}



      String coins(double change) {
    String answer = ":";

    if (change >= 4000) // give two £20 note change
    {
        answer += "\nTwo £20 note";
        change -= 4000;
    }
    if (change >= 2000) // give a £20 note change
    {
        answer += "\nOne £20 note";
        change -= 2000;
    }
    if (change >= 1500) // give £15 note change, a £10 note and a £5 note.
    {
        answer += "\nOne £10 note,\nOne £5 note ";
        change -= 1500;
    }
    if (change >= 1000) // give a £10 note change
    {
        answer += "\nOne £10 note";
        change -= 1000;
    }
    if (change >= 500) // give a £5 note change
    {
        answer += "\nOne £5 note";
        change -= 500;
    }

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。

javax.swing.JOptionPane.showMessageDialog(this, "Your change is " + pounds.format(change / 100)+ coins (change), "change", JOptionPane.INFORMATION_MESSAGE);

在致电coins(double change)时,您传递的是负面参数。

假如你想要扣除2000,那么你正在传递count=-2000

-2000/100 = -20

所以在执行上述语句后,您将获得负值。如果您想要更多解释,请告诉我。