0

每当我在文本框中输入数字并获取文本并将其转换时,我都会遇到异常:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

这是该类的代码:

数字生成器:

package Main;

public class Number_Generator {

    public int makeRandom(){
        int Rnumber = 1;
        Rnumber = 1 + (int)(Math.random()*20);
        return Rnumber;
    }



}

操作添加:

package Main.Oper_classes;
import Main.Number_Generator;
import javax.swing.*;
import java.awt.*;
import Main.Oper_check.*;

public class Oper_add {

    Number_Generator gen = new Number_Generator();
    public JTextField textbox = new JTextField(2);
    //make random numbers
            public Integer Rnumber1 = gen.makeRandom();
            public Integer Rnumber2 = gen.makeRandom();


    public void main(){
        //set textbox to null
        this.textbox.setText(null);

        //import classes
        Add_Check check = new Add_Check();
        //convert to String
        String Rnumber1S = Rnumber1.toString();
        String Rnumber2S = Rnumber2.toString();

        //make GUI
        JFrame frame = new JFrame("Addition Test");
        JPanel panel = new JPanel();
        FlowLayout fl = new FlowLayout();
        panel.setLayout(fl);

        JLabel num1 = new JLabel(Rnumber1S);
        JLabel sign = new JLabel("+");
        JLabel num2 = new JLabel(Rnumber2S);
        JLabel equals = new JLabel("=");
        JButton confirm = new JButton("Check");

        //add action listener
        confirm.addActionListener(check);

        //add componets to window
        panel.add(num1);
        panel.add(sign);
        panel.add(num2);
        panel.add(equals);
        panel.add(textbox);
        panel.add(confirm);

        //set frame settings
        frame.setContentPane(panel);
        frame.setVisible(true);
        frame.pack();

    }

}

添加检查:

package Main.Oper_check;
import java.awt.event.*;
import javax.swing.JOptionPane;
import Main.Oper_classes.*;


public class Add_Check implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        Oper_add add = new Oper_add();

        String textbox = add.textbox.getText().trim();
        Integer textboxC = Integer.parseInt(textbox);
        Integer total = add.Rnumber1 + add.Rnumber2;


    }

}
4

2 回答 2

2
Oper_add add = new Oper_add();
String textbox = add.textbox.getText().trim();
Integer textNumber = Integer.parseInt(textbox);

您正在创建一个新Oper_add的,其中有一个新的空文本框。您期望该文本框有一个值,但它不会。它与您正在与之交互的任何文本框都没有任何关系。

于 2013-04-25T00:38:40.133 回答
1

文本框当前有一个空字符串(或者可能只是空格 -trim删除空格)。它没有空值。例外是因为空字符串不是有效数字。您应该捕获异常,然后在 JOptionPane 中使用它:

try {
    Integer textNumber = Integer.parseInt(textbox);
     ...
} catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(this, ex.getMessage(), "Number Error", JOptionPane.ERROR_MESSAGE);
}
于 2013-04-25T00:23:46.013 回答