2014-04-14 7 views
0
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) 

.NumberFormatException .getText()에서 문자열을 파싱 할 때.

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

위에서 언급 한 오류가 발생합니다. 빈 문자열을 파싱했기 때문에 그랬다고 가정합니다. 그러나 정확히 어디서 정확하게 찾을 수 있었습니까? 그것은 오류의 첫 번째 줄에 합계를 표시하지만 입력은 아직 주어지지 않았습니다. 나는 잠시 동안 이것을보고 있었고, 눈을 가진 새로운 쌍이 문제를 볼 수 있기를 바랍니다. 나는 그것 때문에 빈 문자열을 구문 분석의 가정

+0

'총계 :'는 숫자로 덮어 쓸 수 없습니다 – Braj

답변

3

,

아니, 구문 분석을 시도하는 문자열 (당신이 assumming되는 라벨을 제거 할 수 Total: 8.78

빠른 방법이기 때문이다 레이블을 제외하고 그것에서

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

'빈 문자열 '때문이 아닙니다. 그것의 합계로 인해. – Braj

+1

'val = Double.parseDouble (입력); –

2

제어 당신이 문자열을 구문 분석하려고 보여주고있다 : "Total: 8.78" 난에 옹호자. Total: String을 제거한 다음 동일한 문자열을 구문 분석하십시오.


그것은 좋아하세요 :

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

이 시도하고 당신이 더 도움이 필요하면 알려 주시기 바랍니다.

관련 문제