尝试从 .getText() 解析字符串时出现 NumberFormatException; [英] NumberFormatException when trying to parse Strings from .getText();

查看:31
本文介绍了尝试从 .getText() 解析字符串时出现 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();
        }
    }       
}

我收到了上面提到的错误.我认为这是因为解析了一个空字符串,但我无法准确指出在哪里.它在错误的第一行显示总数,但尚未给出任何输入.我已经研究了一段时间了,希望有经验的新人能看到这个问题.

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.

推荐答案

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

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

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

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

这篇关于尝试从 .getText() 解析字符串时出现 NumberFormatException;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆