将jtextfield转换为int的Numberformat异常

时间:2016-12-31 18:37:54

标签: java integer numberformatexception parseint

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

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

    }
}

异常

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)

1 个答案:

答案 0 :(得分:5)

这一行:

int num1 = Integer.parseInt(textField.getText());

相当于

int num1 = Integer.parseInt("");

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

private JTextField textField = new JTextField();

因此,您尝试将空字符串解析为整数,但它会抛出NumberFormatException,因为它不是整数。

如果您只想解决这些问题,可以在那里放3个整数:

private JTextField textField = new JTextField("1");
private JTextField textField_1 = new JTextField("2");
private JTextField textField_2 = new JTextField("3");

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

int num1 = Integer.parseInt(textField.getText());
int num2 = Integer.parseInt(textField_1.getText());

上述说明可帮助您避免该异常。

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

    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) + "");
        }
    });

其中getIntegerValue可能如下所示:

private int getIntegerValue(String s) {
    if ( "".equals(s) ) {
        return 0;
    }
    return Integer.parseInt(s);
}

或更短:

private int getIntegerValue(String s) {
    return "".equals(s) ? 0 : Integer.parseInt(s);
}

此方法:

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

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