Hot questions for Using JTextField in numberformatexception

Top Java Programmings / JTextField / numberformatexception

Question:

This is the Code and when i input a letter it would not display the line .matches instead i got an error but if i remove the parseFloat rec1 and remove the else if (rec1 < total) then the .matches line will display please help me how to do this thank you in advance

CashType c = new CashType(); c.setVisible(true);

    c.jButton1.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent evt) {
         String receive = c.jTextField1.getText();


         float total = total("sellno"+SellNoCount.getText());
         float rec1 = Float.parseFloat(receive); //this is line 1525

            if(!receive.matches("[0-9]+")){
                JOptionPane.showMessageDialog(null,"Enter a Valid Amount");
                c.jTextField1.setText("");

            }

            else if(receive.equalsIgnoreCase("")){
                JOptionPane.showMessageDialog(null,"Enter Amount");
            }
            else if(rec1 < total){

              JOptionPane.showMessageDialog(null,"Insufficient Amount");

            }

//ERROR

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "asdasd"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at projectfinal.SellPage$32.actionPerformed(SellPage.java:1525)

Answer:

From the error message, it look like you are entering "asdasd" to jTextField1. This value you are trying to parse to float. Float.parseFloat(string) will throw a NumberFormatException if the String is not a numeric. In parseFloat() method, the string parameter will be converted to a primitive float value.

You can check the value entered is numeric or not and then parse it to float.

float rec1 = 0;

   if(isNumeric(receive)){
       rec1 = Float.parseFloat(receive);
       if(rec1 < total){

         JOptionPane.showMessageDialog(null,"Insufficient Amount");

       }
   }else {
          JOptionPane.showMessageDialog(null,"Enter a Valid Amount");
            c.jTextField1.setText("");
         }

The method is

 public static boolean isNumeric(String s) {  
    return s.matches("[-+]?\\d*\\.?\\d+");  
} 

Question:

The Java applet has a working code, I think. However, I am not getting my program executed the way I want it to.

Here is the message it shows when it runs (on parsing JTextField input):

java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at skiRace.init(skiRace.java:24)
    at ready.AppletRunner.run(AppletRunner.java:209)
    at java.lang.Thread.run(Unknown Source)

Here is my code:

import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class skiRace extends Applet implements ActionListener
{
int txt = 0;
int txt2 = 0;
int txt3 = 0;
int txt4 = 0;

public void init ()
{
    resize (300, 350);
    setBackground (Color.blue);
    JLabel pic = new JLabel (createImageIcon ("race.jpg"));

    JLabel ins = new JLabel ("Enter the number of points beside each skier.");
    ins.setFont (new Font ("Arial", Font.BOLD, 12));

    JLabel p1 = new JLabel (createImageIcon ("player1.jpg"));
    JTextField answer = new JTextField (3);
    int txt = Integer.parseInt (answer.getText ());

    JLabel p2 = new JLabel (createImageIcon ("player2.jpg"));
    JTextField answer2 = new JTextField (3);
    int txt2 = Integer.parseInt (answer2.getText ());

    JLabel p3 = new JLabel (createImageIcon ("player3.jpg"));
    JTextField answer3 = new JTextField (3);
    int txt3 = Integer.parseInt (answer3.getText ());

    JLabel p4 = new JLabel (createImageIcon ("player4.jpg"));
    JTextField answer4 = new JTextField (3);
    int txt4 = Integer.parseInt (answer4.getText ());

    JButton done = new JButton ("Done");
    done.setActionCommand ("done");
    done.addActionListener (this);

    add (pic);
    add (ins);
    add (p1);
    add (answer);
    add (answer2);
    add (answer3);
    add (answer4);
    add (done);

}


public void actionPerformed (ActionEvent e)
{
    if (e.getActionCommand ().equals ("done"))
    {
        if ((txt == 7) && (txt2 == 8) && (txt3 == 6) && (txt4 == 9))
        {
            JOptionPane.showMessageDialog (null, "You got it! Great work!", "Correct",
                    JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog (null, "You are incorrect, please try again.",
                    "Incorrect", JOptionPane.ERROR_MESSAGE);
        }
    }
}


protected static ImageIcon createImageIcon (String path)
{
    java.net.URL imgURL = dice.class.getResource (path);
    if (imgURL != null)
    {
        return new ImageIcon (imgURL);
    }
    else
    {
        System.err.println ("Couldn't find file: " + path);
        return null;
    }
}
}

Why is this happening?

I think it has something to do with the dialog boxes or text fields with input, since this is my first program using either of those two functions in a Java applet.


Answer:

Since this line (# 24) is in the init() method:

int txt = Integer.parseInt (answer.getText ());

answer will have the exact same text it was constructed with (i.e. nothing - an empty string). An empty string is not an integer or parsable to an integer.


I would recommend instead:

  • Create a SpinnerNumberModel and keep a reference to that model. Add the model in the constructor of a JSpinner instead of the JTextField.
  • Act on the number (obtained by querying the model) either when the value of the spinner changes, or when the user activates a button, rather than directly after it was created and before the user ever sees the control, let alone gets to change it.

Other notes:

  • Don't 'shadow' variables. E.G.

    int txt4 = 0;
    

    is declared as a class attribute, but it is declared again as a local variable within the init() method. E.G.

    int txt4 = Integer.parseInt (answer4.getText ());
    

    To fix it, change that to:

    txt4 = Integer.parseInt (answer4.getText ()); // use class attribute to store result
    

Question:

I've tried many things and I still can't seem to fix this error no matter what so I'm going to ask my own question.

I keep believing that the error is at the ActionEvent where I try to convert the JTextfield into an int but it might be something else? Thanks :)

I have an object in another class that I need to send the data to in order to construct it. This is the object

/**
 * Constructor
 */
public Account(int startAmount, int balance, int credit, String Name, String    Address)  {       
    openingBalance = startAmount;
    currentBalance = balance;
    creditLimit = credit;
    accountName = Name;
    accountAddress = Address;

    numOfAccounts++;
}

And now the rest of my code,

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;

public class AccountGUI extends JFrame{


private static final long serialVersionUID = 1L;

String Name;
String Address;
int balance;
int credit;
GridBagConstraints gbc = new GridBagConstraints();

public AccountGUI(){

    setLayout(new GridBagLayout());

    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.ipadx = 20;
    gbc.ipady = 20;

    JLabel enterYourName = new JLabel("Name:");
    JTextField textBoxToEnterName = new JTextField(20);
    JPanel firstPanel = new JPanel();
    addHelper(enterYourName,0,0);
    addHelper(textBoxToEnterName,1,0);

    JLabel enterYourAddress = new JLabel("Address:");
    JTextField textBoxToEnterAddress = new JTextField(20);
    addHelper(enterYourAddress,0,1);
    addHelper(textBoxToEnterAddress,1,1);

    JLabel enterYourBalance = new JLabel("Current Balance:");
    JTextField textBoxToEnterBalance = new JTextField(0);
    addHelper(enterYourBalance, 0,2);
    addHelper(textBoxToEnterBalance, 1,2);

    JLabel enterYourCreditLimit = new JLabel("Credit Limit:");
    JTextField textBoxToEnterCreditLimit = new JTextField(20);
    addHelper(enterYourCreditLimit, 0, 3);
    addHelper(textBoxToEnterCreditLimit, 1,3);

    JButton submit = new JButton("Submit");
    submit.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            Name = enterYourName.getText();
            Address = enterYourAddress.getText();
            try {
                int balance = Integer.parseInt(enterYourBalance.getText().trim());
            }
            catch(NumberFormatException ex)
            {
                System.out.println("Exception : "+ex);
            }
            try {
                int credit = Integer.parseInt(enterYourCreditLimit.getText().trim());
            }
            catch(NumberFormatException ex)
            {
                System.out.println("Exception : "+ex);
            }
            Account record = new Account(0, balance, credit, Name, Address);
        }
    });
    addHelper(submit,0,4);

    setTitle("AccountGUI");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(null);


}

private void addHelper(JComponent item, int x, int y){
    gbc.gridx= x;
    gbc.gridy= y;
    add(item,gbc);
}

public static void main(String[] args) {
    AccountGUI promptForName = new AccountGUI();
    promptForName.setVisible(true); 
}


}

The error message I get is

Exception : java.lang.NumberFormatException: For input string: "Current Balance:" 
Exception : java.lang.NumberFormatException: For input string: "Credit Limit:"

Answer:

JLabel enterYourBalance = new JLabel("Current Balance:");
JTextField textBoxToEnterBalance = new JTextField(0);
...
int balance = Integer.parseInt(enterYourBalance.getText().trim());`

enterYourBalance.getText().trim() will return "Current Balance:" and parsing it to int fails. Change to textBoxToEnterBalance.getText().trim() to get the text from the text field.

Question:

I have this error:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
    at Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at sunat.calculadora.btnCalcularActionPerformed(calculadora.java:234)
    at sunat.calculadora.access$100(calculadora.java:14)
    at sunat.calculadora$2.actionPerformed(calculadora.java:109)
    at 

My code:

private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {                                            
 int sueldo,gratificaciones;
 int renumeracion_bruta_anual;
 int horas_extras,meses_pendientes;
 int renumeracion_neta_anual;
 double  impuesto_anual_proyectado;
 int asignacion_familiar;

 horas_extras=0;

 sueldo=Integer.parseInt(txtsueldo.getText());
 horas_extras = Integer.parseInt(txthorasextras.getText());



 meses_pendientes=Integer.parseInt(txtmesespendientes.getText());
 gratificaciones=Integer.parseInt(txtgratificacion.getText());
 asignacion_familiar=Integer.parseInt(txtasignacionfamiliar.getText());



 renumeracion_bruta_anual=sueldo*meses_pendientes+gratificaciones+horas_extras+asignacion_familiar;
 renumeracion_neta_anual=renumeracion_bruta_anual-29400;





 if (renumeracion_neta_anual<1){
       JOptionPane.showMessageDialog (null, "Usted no paga impuesto");
       }

 if (renumeracion_neta_anual <= 21000 && renumeracion_neta_anual>=1) {

 impuesto_anual_proyectado=renumeracion_neta_anual*0.08;
 txtcalculo.setText(String.format("%.2f", impuesto_anual_proyectado));

 } else if (renumeracion_neta_anual > 21000 && renumeracion_neta_anual<=84000) {
 impuesto_anual_proyectado=renumeracion_neta_anual *0.14;
  txtcalculo.setText(String.format("%.2f", impuesto_anual_proyectado));
 } else if (renumeracion_neta_anual > 84000 && renumeracion_neta_anual<=147000) {
 impuesto_anual_proyectado=renumeracion_neta_anual *0.17;
 txtcalculo.setText(String.format("%.2f", impuesto_anual_proyectado));
 } else if (renumeracion_neta_anual >147000 && renumeracion_neta_anual<=18900) {

 impuesto_anual_proyectado=renumeracion_neta_anual *0.20;
 txtcalculo.setText(String.format("%.2f", impuesto_anual_proyectado));
 } else if (renumeracion_neta_anual >18900) {
 impuesto_anual_proyectado=renumeracion_neta_anual *0.30;
 txtcalculo.setText(String.format("%.2f", impuesto_anual_proyectado));



 }         

} 

As you can see the field hours_extras is declared as an integer but at the moment leaving the field hours_extras empty it becomes String and does not perform the mathematical operation giving the error above. There is some way to let go without writing anything in the jtexfield since I must leave that field empty and calculate the final amount without it when it is not required. Thank you for your answers.


Answer:

You can do something like the following if you have to handle empty strings as a special case, and would like gibberish inputs to still throw an Exception:

String extraHourString = txthorasextras.getText();
if(extraHourString.isEmpty()) { //alternatively, if(extraHourString.equals("")) {
    ... //handle the text being empty, or set a boolean flag so that you can handle it later
}
else { // we know the provided text is not empty now
    //will still crash on gibberish inputs, but the empty string "" will never reach here
    horas_extras = Integer.parseInt(extraHourString);
}

Alternatively, if you would like to completely ignore the empty string (leaving horas_extras to a default value), you can do something like the following:

int horas_extras = DEFAULT_VALUE; //declaration sets the default (could be any integer)
...
if(!txthorasextras.getText().equals("")) { //or, if(!txthorasextras.getText().isEmpty()) {
    horas_extras = Integer.parseInt(txthorasextras.getText());
}

This will ignore the assignment to horas_extras if the input string is empty, which will leave it at the current value of horas_extras (DEFAULT_VALUE). Note that gibberish inputs still throw an Exception as before.

Question:

So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.

I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.

When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.

Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.

This is the code:

private String cValue; 
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;

/**
 * Create the frame.
 */
public CelsiusConverter() {

    setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
    setBounds(100, 100, 194, 134);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblCelsius = new JLabel("Celsius");
    lblCelsius.setBounds(10, 11, 61, 14);
    contentPane.add(lblCelsius);

    celsiusField = new JTextField();
    celsiusField.setBounds(81, 8, 86, 20);
    contentPane.add(celsiusField);
    celsiusField.setColumns(10);

    JLabel lblFahrenheit = new JLabel("Fahrenheit:");
    lblFahrenheit.setBounds(10, 73, 70, 14);
    contentPane.add(lblFahrenheit);

    JLabel lblResult = new JLabel();
    lblResult.setText(String.valueOf(result));
    lblResult.setBounds(81, 73, 87, 14);
    contentPane.add(lblResult);     
    cValue = celsiusField.getText();

    convertButton = new JButton("Convert");
    convertButton.setBounds(10, 39, 157, 23);
    contentPane.add(convertButton);
    convertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int parsed = Integer.parseInt(cValue);
        }           
    });
}

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CelsiusConverter frame = new CelsiusConverter();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

And this is the error:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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)

Answer:

cValue = celsiusField.getText();

You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.

You need to get the text from the text field in your ActionListener

String cValue = celsiusField.getText();
int parsed = Integer.parseInt(cValue);