Java 出现 NumberFormatException 和 parseInt 错误的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21889618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:16:54  来源:igfitidea点击:

Error with a NumberFormatException and parseInt error

javaswingparseintnumberformatexception

提问by engz

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

我正在创建一个简单的 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;

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:

我在那里接受输入,转换为字符串,然后转换为整数,以便我可以在 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.run(app.java:30)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access0(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain.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:

我不知道为什么,但它已经这样做了将近 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);

    }
}

采纳答案by helderdarocha

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.

您的字段为空,您正在尝试将空字符串转换为数字(通过parseInt())。这就是导致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.

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

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

回答by Sembrano

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.

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

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.

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

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.

您还应该添加一些逻辑,这样就不可能传入空字符串或捕获空字符串或双精度值。因为每次用户没有输入正确的数字格式都会导致此异常。