JAVA - 忽略 getText 中的“$”

JAVA - Ignoring '$' in getText

我 运行 遇到了学校作业的问题,我们必须为一家快餐公司创建 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 框中保留“$”但仍然能够正确计算零钱?

需要从文本中删除 $ 和逗号,以便将其解析为 double 数字。您可以通过链接 String#replace 来实现,首先用空白文本替换 ,,然后用空白文本替换 $

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

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