NumberFormatException when trying to parse Strings

2019-03-06 11:39发布

问题:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input       string: "Total: 8.78"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at PizzaOrder$BtnClicked.<init>(PizzaOrder.java:298)
at PizzaOrder$BtnClicked.<init>(PizzaOrder.java:295)
at PizzaOrder.addListeners(PizzaOrder.java:102)
at PizzaOrder.<init>(PizzaOrder.java:76)
at PizzaDriver$1.run(PizzaDriver.java:46)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source) 

.

    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.*;


    /**
     * Window for ordering a pizza<br>
     *
     * <hr>
     * Date created: Apr 14, 2014<br>
     * <hr>
     * @author Zach Latture
     */
    public class PizzaOrder extends JFrame
    {
    private static final long   serialVersionUID    = 1L;
    public static final double  PIZZACOST = 8.00, 
                                TAXRATE = 0.0975;
    private JPanel              headerPanel, 
                                checkPanel, 
                                buttonsPanel;
    private JLabel              pizzaLbl;
    private JCheckBox           pepperoni, 
                                sausage, 
                                peppers, 
                                onions, 
                                mushrooms, 
                                cheese;
    private JTextField          numberOfPizzas;
    private JLabel              totalLbl, 
                                subtotalLbl;
    private JLabel              taxLbl;
    private NumberFormat        fmt = new DecimalFormat();
    private JButton             submit, 
                                cancel;
    private double              subtotal = 0;
    private double              tax = 0;
    private double              total = 0;

    public PizzaOrder()
    {
        super ("Pizza Order - Latture");
        this.setSize(250, 250);
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(2, 5));

        initComponents ( );  // instantiate and initial all labels, textfields, etc.

        initHeaderPanel ( ); // put label and textfield in header panel
        add(headerPanel, BorderLayout.NORTH);

        initCheckPanel ( );  // put the checkboxes and totals in the CheckPanel
        add(checkPanel, BorderLayout.CENTER);

        initButtonPanel ( ); // put the buttons in the button panel
        add(buttonsPanel, BorderLayout.SOUTH);

        calculate();    // calculate the subtotal, tax, and total

        addListeners ( );  // register listeners for all needed events

        setLocationRelativeTo(null);
        setVisible(true);
    }

    /**
     * add listeners for all events <br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     * Date last modified: Apr 14, 2014 <br>
     *
     * <hr>
     */
    private void addListeners ( )
    {
        // Register listeners for all events for the components
        // such as buttons, checkboxes, etc.
        pepperoni.addItemListener(new Listener());
        sausage.addItemListener(new Listener());
        peppers.addItemListener(new Listener());
        onions.addItemListener(new Listener());
        mushrooms.addItemListener(new Listener());
        cheese.addItemListener(new Listener());

        submit.addActionListener(new BtnClicked());
        cancel.addActionListener(new BtnClicked());
    }

    /**
     * add buttons to button panel <br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     *
     * <hr>
     */
    private void initButtonPanel ( )
    {
        buttonsPanel = new JPanel(new FlowLayout());
        buttonsPanel.add (submit);
        buttonsPanel.add (cancel);
    }

    /**
     * Init checkboxes and totals <br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     *
     * <hr>
     */
    private void initCheckPanel ( )
    {
        checkPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 1));
        checkPanel.add (pepperoni);
        checkPanel.add (sausage);
        checkPanel.add (peppers);
        checkPanel.add (onions);
        checkPanel.add (mushrooms);
        checkPanel.add (cheese);
        checkPanel.add (subtotalLbl);
        checkPanel.add (taxLbl);
        checkPanel.add (totalLbl);
        // Add the checkboxes and labels for the totals and tax
    }

    /**
     * Add label and textfield to header panel <br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     *
     * <hr>
     */
    private void initHeaderPanel ( )
    {
        headerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        headerPanel.add (pizzaLbl);
        headerPanel.add (numberOfPizzas);
    }

    /**
     * instantiate the buttons, checkboxes, labels, etc.<br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     *
     * <hr>
     */
    private void initComponents ( )
    {
        submit = new JButton("Submit");
        cancel = new JButton("Cancel");
        fmt = NumberFormat.getCurrencyInstance ( );


        pizzaLbl = new JLabel("Number of pizzas");
        totalLbl = new JLabel("Total:");
        subtotalLbl = new JLabel("Subtotal:");
        taxLbl = new JLabel("Tax: ");

        numberOfPizzas = new JTextField("3");
        numberOfPizzas.setText("1");

        pepperoni = new JCheckBox("Pepperoni");
        sausage = new JCheckBox("Sausage"); 
        peppers = new JCheckBox("Peppers"); 
        onions = new JCheckBox("Onions"); 
        mushrooms = new JCheckBox("Mushrooms"); 
        cheese = new JCheckBox("Extra Cheese");


    }

    /**
     * Use the values selected and entered to determine the cost<br>        
     *
     * <hr>
     * Date created: Apr 14, 2014 <br>
     *
     * <hr>
     */
    public void calculate()
    {
        subtotal = 0;

        double increase = 0;
        String input = numberOfPizzas.getText();
        double val = 0, determinedTotal, determinedSubtotal, determinedTax;
        val = numberOfPizzas.getValue().doubleValue();

        try
        {
            val = Double.parseDouble(input);
        }catch(Exception e)
        {
            System.out.print("Invalid input. Error: " + e.getMessage());
        }


        determinedSubtotal = val * PIZZACOST;
        determinedTax = determinedSubtotal * TAXRATE;
        determinedTotal = determinedSubtotal + determinedTax;

        if(pepperoni.isSelected())
        {
            pepperoni.setSelected(true); 
            increase += val * 1.00;

        }

        if(sausage.isSelected())
        {
            sausage.setSelected(true);
            increase += val * 1.00;
        }

        if(peppers.isSelected())
        {
            peppers.setSelected(true);
            increase += val * .50;
        }

        if(onions.isSelected())
        {
            onions.setSelected(true);
            increase += val * .50;
        }

        if(mushrooms.isSelected())
        {
            mushrooms.setSelected(true);
            increase += val * .50;
        }

        if(cheese.isSelected())
        {
            cheese.setSelected(true);
            increase += val * 1.00;
        }


        subtotalLbl.setText("Subotal: " +String.valueOf(determinedSubtotal + increase));
        taxLbl.setText("Tax: " +String.valueOf(determinedTax + increase));
        totalLbl.setText("Total: " + String.valueOf(determinedTotal + increase));

        numberOfPizzas.grabFocus ( );
        numberOfPizzas.selectAll ( );
        return;
    }

    /**
     * Class handles ItemStateChanged events for checkboxes<br>
     *
     * <hr>
     * Date created: Apr 14, 2014<br>
     * <hr>
     * @author Zach Latture
     */
    private class Listener implements ItemListener
    {
        // Appropriate method calculates the results
        public void itemStateChanged(ItemEvent e)
        {
            calculate();
        }

    }

    /**
     * Class handles button clicked events for both buttons<br>
     *
     * <hr>
     * Date created: Apr 14, 2014<br>
     * <hr>
     * @author Zach Latture
     */
    private class BtnClicked implements ActionListener
    {
        String input = totalLbl.getText();
        Double d = Double.parseDouble(input) * 0.20;

        public void actionPerformed(ActionEvent e)
        {

            Object src = e.getSource();
            if(src == submit)
            {
                JOptionPane.showMessageDialog (null, "Thank you for your order - the tip will be" + fmt.format(d),"Thank you.", 1);
            }
            else if(src == cancel)
            {
                JOptionPane.showMessageDialog (null, "Order cancelled","Thank you.", 1);
            }
        }

        /**
         * Reset the choices to their defaults<br>        
         *
         * <hr>
         * Date created: Apr 14, 2014 <br>
         *
         * <hr>
         */ 
        private void reset ( )
        {
            // Set the checkboxes and text fields to their original values

            calculate();
        }
    }       
}

i'm getting the error mentioned above. I assume it's because of parsing an empty string, but i haven;t been able to pinpoint exactly where. It's displaying the total in the first line of the error, yet no input has been given yet. I've been looking at this for a while now, and hopefully a new pair experienced of eyes can see the problem.

回答1:

I assume it's because of parsing an empty string,

No it is because the String it is attempting to parse is Total: 8.78

quick way to remove that label is (assumming you have control over the label

substring("Total:".length()).trim();


回答2:

From the exception it is showing you are trying to parse string: "Total: 8.78" to integer. Try to remove Total: String then parse the same.

Do it like:

String input = totalLbl.getText();
input = input.replace("Total:","").trim();
Double d = Double.parseDouble(input) * 0.20;

Please try this and let me know if you need further help.