尝试从.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.(PizzaOrder.java:298) at PizzaOrder$BtnClicked.(PizzaOrder.java:295) at PizzaOrder.addListeners(PizzaOrder.java:102) at PizzaOrder.(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
* *
* Date created: Apr 14, 2014
*
* @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
* *
* Date created: Apr 14, 2014
* Date last modified: Apr 14, 2014
* *
*/ 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
* *
* Date created: Apr 14, 2014
* *
*/ private void initButtonPanel ( ) { buttonsPanel = new JPanel(new FlowLayout()); buttonsPanel.add (submit); buttonsPanel.add (cancel); } /** * Init checkboxes and totals
* *
* Date created: Apr 14, 2014
* *
*/ 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
* *
* Date created: Apr 14, 2014
* *
*/ private void initHeaderPanel ( ) { headerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); headerPanel.add (pizzaLbl); headerPanel.add (numberOfPizzas); } /** * instantiate the buttons, checkboxes, labels, etc.
* *
* Date created: Apr 14, 2014
* *
*/ 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
* *
* Date created: Apr 14, 2014
* *
*/ 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
* *
* Date created: Apr 14, 2014
*
* @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
* *
* Date created: Apr 14, 2014
*
* @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
* *
* Date created: Apr 14, 2014
* *
*/ private void reset ( ) { // Set the checkboxes and text fields to their original values calculate(); } } }

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

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

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

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

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

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

这样做:

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

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