我想使用 NumberFormatException
但我的代码有错误,因为我的程序中有 TextField
和一个按钮。如果您在文本字段中输入数字,则没有任何问题。
如果你输入一个字母,我想得到错误消息但我不使用。请帮助我?
我的代码
private JTextField t1=new JTextField(10);
private JButton o88 = new JButton("send");
try{
o88.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int a = 0;
a = Integer.parseInt(t1.getText());
}
});
}
catch (NumberFormatException e){
System.out.println( e.getMessage());
}
最佳答案
你的 try/catch 放在了错误的地方。您需要将其放在 actionPerformed 方法中。
public void actionPerformed(ActionEvent e ) {
try {
int a = Integer.parseInt( t1.getText() );
}
catch(NumberFormatException e ) {
System.out.println( e.getMessage() );
}
}
关于Java数字格式异常使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20723408/