**RESOLVIDO **Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String

Pessoas, sou novo em java e estou criando um projeto para calcular compras em um mercadinho por peso, porém quando vou tentar da esse erro que não consigo entender.

Exception in thread “AWT-EventQueue-0” java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at mercadinho.mercadinhotela.comprarActionPerformed(mercadinhotela.java:298)
at mercadinho.mercadinhotela.access$200(mercadinhotela.java:18)
at mercadinho.mercadinhotela$3.actionPerformed(mercadinhotela.java:150)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

o meu código é esse:

package mercadinho;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

/**
*

  • @author gumiq
    */
    public class mercadinhotela extends javax.swing.JFrame {

    public mercadinhotela() {
    initComponents();
    centralizar();
    }

    public void centralizar(){
    Dimension ds = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension dw = getSize();
    setLocation((ds.width - dw.width) / 2, (ds.height - dw.height)/2);
    }

    private void initComponents() {

     jPanel1 = new javax.swing.JPanel();
     jLabel1 = new javax.swing.JLabel();
     jLabel2 = new javax.swing.JLabel();
     jLabel3 = new javax.swing.JLabel();
     batata = new javax.swing.JCheckBox();
     cenoura = new javax.swing.JCheckBox();
     cebola = new javax.swing.JCheckBox();
     bete = new javax.swing.JCheckBox();
     pepino = new javax.swing.JCheckBox();
     pimentao = new javax.swing.JCheckBox();
     tomate = new javax.swing.JCheckBox();
     jLabel4 = new javax.swing.JLabel();
     jLabel5 = new javax.swing.JLabel();
     jLabel6 = new javax.swing.JLabel();
     jLabel7 = new javax.swing.JLabel();
     jLabel8 = new javax.swing.JLabel();
     jLabel9 = new javax.swing.JLabel();
     jLabel10 = new javax.swing.JLabel();
     qbatata = new javax.swing.JTextField();
     qcenoura = new javax.swing.JTextField();
     qcebola = new javax.swing.JTextField();
     qbete = new javax.swing.JTextField();
     qpepino = new javax.swing.JTextField();
     qpimentao = new javax.swing.JTextField();
     qtomate = new javax.swing.JTextField();
     comprar = new javax.swing.JButton();
     jScrollPane1 = new javax.swing.JScrollPane();
     mostrartotal = new javax.swing.JTextArea();
     jLabel11 = new javax.swing.JLabel();
    

    }

    private void comprarActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

     double xbatata = Double.parseDouble(qbatata.getText());
     double xcenoura = Double.parseDouble(qcenoura.getText());
     double xcebola = Double.parseDouble(qcebola.getText());
     double xbete = Double.parseDouble(qbete.getText());
     double xpepino = Double.parseDouble(qpepino.getText());
     double xpimentao = Double.parseDouble(qpimentao.getText());
     double xtomate = Double.parseDouble(qtomate.getText());
     
     double compra;
     
     
     if(batata.isSelected()){
         xbatata = xbatata * 1.50;    
     }
     if(cenoura.isSelected()){
         xcenoura = xcenoura * 2.00;
     }
     if(cebola.isSelected()){
         xcebola = xcebola * 3.10;
     }
     if(bete.isSelected()){
         xbete = xbete * 2.35;
     }
     if(pepino.isSelected()){
         xpepino = xpepino * 1.85;
     }
     if(pimentao.isSelected()){
         xpimentao = xpimentao * 3.00;
     }
     if(tomate.isSelected()){
         xtomate = xtomate * 3.50;
     }
     compra = xbatata + xcenoura + xcebola + xbete + xpepino + xpimentao + xtomate;
     
     DecimalFormat formato = new DecimalFormat("###.##") ;
     
     mostrartotal.setText("R$" + Double.toString((compra)));

O erro java.lang.NumberFormatException: empty String (Exceção de Formato Numérico: string vazia). Ou seja, você está tentando formatar para número uma string vazia aqui:

 double xbatata = Double.parseDouble(qbatata.getText());
 double xcenoura = Double.parseDouble(qcenoura.getText());
 double xcebola = Double.parseDouble(qcebola.getText());
 double xbete = Double.parseDouble(qbete.getText());
 double xpepino = Double.parseDouble(qpepino.getText());
 double xpimentao = Double.parseDouble(qpimentao.getText());
 double xtomate = Double.parseDouble(qtomate.getText());

Isso se deve ao fato de que provavelmente você não definiu que os campos de textos sejam inicializados. Assim, quando tu abre o programa, esses campos vêm vazios. Assim, como pode haver uma formatação de uma string vazia?

Segundo a Documentação do Java para o método parseDouble(String str):

Retorna um novo número de ponto flutuante de dupla precisão (double) inicializado para o valor representado pela String especificada, conforme executado pelo método valueOf da classe Double.

O método parseDouble(String str) lança a exceção NumberFormatException, logo, via de regra, a conversão deve ser feita dentro de um bloco try-catch.
Exemplo:

double xbatata;

try{
	xbatata = Double.parseDouble(qbatata.getText());
	
}catch(NumberFormatException nfe){
	System.out.println("ERRO: " + nfe.getMenssage());
}

Ainda segundo a documentação:

Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double
Ou seja,

Lança as seguintes exceções:
1 - Exceção de Ponteiro Nulo (NullPointerException): quando a string é nula (vale null);

2 - Exceção de Formatação Numérica (NumberFormatException): quando a string não contém um valor convertível para double.

Como resolver (duas maneiras):

1 - Você pode inicializar os campos de texto com um valor válido. Assim, ao carregar o programa esses campos terão um valor prévio;
Exemplo:
qbatata = new javax.swing.JTextField("0.00");

2 - Testar se o campo tem um valor válido antes de proceder com a conversão;
Exemplo:
double xbatata = 0.00;

if(!qbatata.getText().isEmpty())
	xbatata = Double.parseDouble(qbatata.getText());
1 curtida

Caaara, muito obrigado, funcionou perfeitamente, valeu mesmo.