Question

I am creating a simple MPG application. It started showing errors after I added:

String strGallons = gallons1.getText();
int gal = Integer.parseInt(strGallons);
String strMiles = miles1.getText();
int mil = Integer.parseInt(strMiles);
int mpg = mil / gal;
String mpgstring = "" + mpg;

I have this there to take the input, convert to string, then convert to an integer so I can use it in the MPG formula. It shows no errors in the code, but once I attempt to run it, it shows this:

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 app.<init>(app.java:83)
at app$1.run(app.java:30)
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)

I don't know why, but it has been doing this for almost 2 days. My full code is:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;

public class app extends JFrame {
    private String StrMiles;
    private String StrGallons;
    private int mil;
    private int gal;
    private int mpg;
    private JPanel contentPane;
    private JTextField gallons1;
    private JTextField miles1;
    private JTextField mpgbox;

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

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

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        gallons1 = new JTextField();
        gallons1.setBounds(10, 39, 86, 20);
        contentPane.add(gallons1);
        gallons1.setColumns(10);

        miles1 = new JTextField();
        miles1.setBounds(10, 83, 86, 20);
        contentPane.add(miles1);
        miles1.setColumns(10);

        JButton calculate = new JButton("CALCULATE");
        calculate.setBounds(204, 80, 110, 23);
        contentPane.add(calculate);

        JLabel gallons = new JLabel("Gallons");
        gallons.setBounds(10, 25, 46, 14);
        contentPane.add(gallons);

        JLabel miles = new JLabel("Miles");
        miles.setBounds(10, 70, 46, 14);
        contentPane.add(miles);

        JLabel mpgtitle = new JLabel("MPG:");
        mpgtitle.setEnabled(false);
        mpgtitle.setBounds(189, 204, 46, 14);
        contentPane.add(mpgtitle);

        String strGallons = gallons1.getText();
        int gal = Integer.parseInt(strGallons);
        String strMiles = miles1.getText();
        int mil = Integer.parseInt(strMiles);
        int mpg = mil / gal;
        String mpgstring = "" + mpg;

        mpgbox = new JTextField();
        mpgbox.setText(mpgstring);
        mpgbox.setEnabled(false);
        mpgbox.setEditable(false);
        mpgbox.setBounds(228, 201, 86, 20);
        contentPane.add(mpgbox);
        mpgbox.setColumns(10);

    }
}
Was it helpful?

Solution

Your field is empty and you are trying to convert an empty string into a number (via parseInt()). That's what is causing the NumberFormatException.

To avoid that kind of exception, you should validate your field. You can write a simple check testing if it's empty by asserting that the length() of the input String returned by getText() is greater than zero.

You can check if it is a number writing a regular expression

String possibleNumber = yourField.getText();
boolean isNumber = Pattern.matches("[0-9]+", possibleNumber);
if(isNumber) {
   number = Integer.parseInt(possibleNumber);
}

But you shouldn't be reading data in the constructor in the first place. Write an event handler to capture the action event of pressing the button, and in it read the data.

yourButton.addActionListener(new ActionListener() {
    yourText = field.getText();
}); 

OTHER TIPS

This exception say :

java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)

your input string here is set to "" aka an empty String and then you try to parse the "" into an int. And that is not possible and therefore the error.

Make sure you pass in correct numbers like 1 2 3 or something and with no dots like 1.2 because that aswell will give an error.

You should also add some logic so its not possible to pass in an empty string or catch the empty string or a double value. Because it will cause this exception everytime user does not input a correct number format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top