尝试从.getText()解析字符串时出现NumberFormatException;

时间:2014-04-14 19:21:43

标签: java string swing numberformatexception

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();
        }
    }       
}

我收到上面提到的错误。我认为这是因为解析了一个空字符串,但我还没有确切地指出确切的位置。它显示错误第一行的总数,但尚未给出任何输入。我已经看了一段时间了,希望有一双经验丰富的眼睛可以看到问题。

2 个答案:

答案 0 :(得分:3)

  

我认为这是因为解析了一个空字符串,

不,这是因为它试图解析的字符串是Total: 8.78

删除该标签的快捷方法是(假设您可以控制标签

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

答案 1 :(得分:2)

从异常中可以看出,您正在尝试将字符串:"Total: 8.78"解析为整数。 尝试删除Total:字符串,然后解析相同的字。

这样做:

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

如果您需要进一步的帮助,请试试这个并告诉我。