NumberFormatException和parseInt错误时出错

时间:2014-02-19 18:49:22

标签: java swing parseint numberformatexception

我正在创建一个简单的MPG应用程序。我添加后开始显示错误:

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;

我在那里接受输入,转换为字符串,然后转换为整数,以便我可以在MPG公式中使用它。它在代码中没有显示错误,但是一旦我尝试运行它,就会显示:

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)

我不知道为什么,但它已经这样做了将近2天。我的完整代码是:

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

    }
}

2 个答案:

答案 0 :(得分:2)

您的字段为空,您正在尝试将空字符串转换为数字(通过parseInt())。这就是造成NumberFormatException

的原因

为了避免这种异常,您应该验证您的字段。您可以通过声明length()返回的输入字符串的getText()大于零来编写一个简单的检查测试,如果它是空的。

您可以检查它是否是编写正则表达式的数字

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

但是你不应该首先在构造函数中读取数据。编写一个事件处理程序来捕获按下按钮的动作事件,并在其中读取数据。

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

答案 1 :(得分:2)

这个例外说:

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

此处的输入字符串设置为""又称为空字符串,然后尝试将""解析为int。这是不可能的,因此也就是错误。

确保传递正确的数字,如1 2 3或其他东西,并且没有像1.2这样的点,因为它也会出错。

您还应该添加一些逻辑,以便无法传入空字符串或捕获空字符串或double值。因为每次用户输入正确的数字格式时都会导致此异常。