将jtextfield转换为int的Numberformat异常

use*_*680 -1 java integer parseint numberformatexception

我一直在寻找其他帖子的答案,他们似乎指出我正在做什么,但我仍然得到NumberFormatException.我试图JFrame通过拉取jtextfield值并将其转换为int 来构建一个简单的计算器,但我得到以下异常.

package com.calculator.app;

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

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CalculatorApp extends JFrame {

    private JPanel contentPane;
    private JTextField textField = new JTextField();
    private JTextField textField_1 = new JTextField();
    private JTextField textField_2 = new JTextField();
    int num1 = Integer.parseInt(textField.getText());
    int num2 = Integer.parseInt(textField_1.getText());
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalculatorApp frame = new CalculatorApp();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

    //  int num2 = Integer.parseInt(value2);    

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

        JLabel lblCalculatorApp = new JLabel("Calculator App");
        lblCalculatorApp.setBounds(141, 37, 138, 23);
        contentPane.add(lblCalculatorApp);

        JButton btnNewButton = new JButton("Add");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

            }
        });
        btnNewButton.setBounds(74, 112, 131, 31);
        contentPane.add(btnNewButton);

        JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(169, 181, 82, 23);
        contentPane.add(lblNewLabel);

        textField = new JTextField();
        textField.setBounds(55, 73, 54, 23);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setColumns(10);
        textField_1.setBounds(151, 70, 54, 23);
        contentPane.add(textField_1);

        textField_2 = new JTextField();
        textField_2.setColumns(10);
        textField_2.setBounds(109, 162, 124, 55);
        contentPane.add(textField_2);
    //  textField_2.setText(String.valueOf(output));
        try{

            int output = Integer.parseInt(textField.getText());
                }
                catch(NumberFormatException e){
                    System.out.println("Error");    
                }

    }
}
Run Code Online (Sandbox Code Playgroud)

例外

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 com.calculator.ap.CalculatorApp.<init>(CalculatorApp.java:23)
    at com.calculator.ap.CalculatorApp$1.run(CalculatorApp.java:32)
    at java.awt.event.InvocationEvent.dispatch(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.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)
Run Code Online (Sandbox Code Playgroud)

ROM*_*eer 5

这一行:

int num1 = Integer.parseInt(textField.getText());
Run Code Online (Sandbox Code Playgroud)

相当于

int num1 = Integer.parseInt("");
Run Code Online (Sandbox Code Playgroud)

因为您没有textField使用此行中的特定值初始化:

private JTextField textField = new JTextField();
Run Code Online (Sandbox Code Playgroud)

所以,你试图将一个空字符串解析为整数,但它会抛出NumberFormatException,因为它不是一个整数.

如果你只是想克服这些问题,可以在那里放3个整数:

private JTextField textField = new JTextField("1");
private JTextField textField_1 = new JTextField("2");
private JTextField textField_2 = new JTextField("3");
Run Code Online (Sandbox Code Playgroud)

或者(更好)你可以删除以下行,因为它似乎需要稍后解析它们(当单击按钮时):

int num1 = Integer.parseInt(textField.getText());
int num2 = Integer.parseInt(textField_1.getText());
Run Code Online (Sandbox Code Playgroud)

上面的解释可以帮助您避免该异常.

但是如果你想对这些数字求和,你应该填写这个方法的主体:

    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String text1 = textField.getText();
            String text2 = textField_1.getText();
            textField_2.setText(getIntegerValue(text1) + getIntegerValue(text2) + "");
        }
    });
Run Code Online (Sandbox Code Playgroud)

在哪里getIntegerValue可以看起来像这样:

private int getIntegerValue(String s) {
    if ( "".equals(s) ) {
        return 0;
    }
    return Integer.parseInt(s);
}
Run Code Online (Sandbox Code Playgroud)

或更短:

private int getIntegerValue(String s) {
    return "".equals(s) ? 0 : Integer.parseInt(s);
}
Run Code Online (Sandbox Code Playgroud)

这个方法:

  • 返回0字符串是否为空(没有值)
  • 如果字符串表示整数,则返回整数
  • NumberFormatException如果字符串不是整数或空字符串,则抛出
  • 不需要抓住NumberFormatException,因为它是一个RuntimeException

当然,if如果要抛出异常,即使字符串为空,也可以从最后一个方法中删除该/ ternary运算符.