Warm tip: This article is reproduced from serverfault.com, please click

character-爪哇

(character - JAVA)

发布于 2020-12-04 20:24:01

我的学校作业遇到了问题,我们必须为一家快餐公司创建一个PoS。部分工作是在输入招标金额后计算变更。我遇到的问题是程序无法从由于“ $”而支付的总额中减去总计。我的代码当前如下所示:


    private void totalButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
          
    // Finding the subtotal
            double burgers;
            double fries;
            double drinks;
            double subtotal;
            
            burgers = 2.49;
            fries = 1.89;
            drinks = 0.99;
            
            subtotal = Double.parseDouble (burgerInput.getText ()) * burgers 
                    + Double.parseDouble (fryInput.getText ()) * fries 
                    + Double.parseDouble (drinkInput.getText ()) * drinks;
           
            
            DecimalFormat w = new DecimalFormat("###,###0.00");
            subtotalOutput.setText("$" + w.format(subtotal));
            
    // Calculating Tax
            double taxpercentage;
            double tax;
            
            taxpercentage = 0.13;
            
            tax = subtotal * taxpercentage;
            
            DecimalFormat x = new DecimalFormat("###,###0.00");
            taxesOutput.setText("$" + x.format(tax));
    
    // Grand Total
            double grandtotal;
            
            grandtotal = subtotal + tax;
            
            DecimalFormat y = new DecimalFormat("###,###0.00");
            grandtotalOutput.setText("$" + y.format(grandtotal));
            
    
                                                  

为了计算变化:


// Calculating Change
        double tendered;
        double grandtotal;
        double change;
        
        tendered = Double.parseDouble(tenderedInput.getText ());
        grandtotal = Double.parseDouble(grandtotalOutput.getText ());
        change = tendered - grandtotal;
        
        DecimalFormat z = new DecimalFormat("###,###0.00");
        changeOutput.setText("$" + z.format(change));
                                             

任何帮助忽略'$'符号以允许我将'$'保留在grandtotalOutput框中但仍能够正确计算更改的帮助将不胜感激。谢谢!

Questioner
INFINITY
Viewed
0
Arvind Kumar Avinash 2020-12-05 04:39:04

$顿号,需要从以文本去除它被解析成double数。你可以通过链接来实现String#replace,首先,用空白文本替换,然后$用空白文本替换

tendered = Double.parseDouble(tenderedInput.getText().replace(",", "").replace("$", ""));
grandtotal = Double.parseDouble(grandtotalOutput.getText().replace(",", "").replace("$", ""));

注意:替换可以以任何顺序进行(即,首先替换$为空白文本,然后,替换为空白文本)。