【问题标题】:JAVA - Ignoring '$' in getTextJAVA - 在getText中忽略'$'
【发布时间】:2021-03-16 21:36:11
【问题描述】:

我的学校作业遇到了问题,我们必须为一家快餐公司创建 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 框中,但仍能正确计算更改?

【问题讨论】:

    标签: java character symbols gettext


    【解决方案1】:

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

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

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

    【讨论】:

    • 这行得通,谢谢 - 程序中必须有 $,所以我必须找到一种方法将其保留在其中(不幸的是,我们老师提供的课程没有超过 .replace() .
    • 即使您的老师不复习,最好阅读有关您正在学习的课程的 JavaDocs(课程的官方文档)。例如,String 上的文档会告诉你很多有趣且有用的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2021-01-18
    • 2016-07-30
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多