我制作了一个小型 GUI 求和程序。程序在空文本字段上运行良好,但问题是当用户在文本字段中输入任何字符串时会发生错误
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "a34dsfsdf"
如何修复字符串类型或除数字之外的任何字符的错误
这是我的代码
private JTextField textfield1;
private JTextField textfield3;
private JTextField textfield4;
private JButton button1;
public ChildClass(){
super("Frame");
button1 = new JButton();
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double number1,baseE,sum;
String text1=textfield1.getText();
String text3=textfield4.getText();
if(text1.isEmpty() && text3.isEmpty()){
JOptionPane.showMessageDialog(null, "Enter Values In TextField", "Invalid TextFields", JOptionPane.ERROR_MESSAGE);
return;
}
else if(!text3.isEmpty() && !text1.isEmpty()){
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
result =number1+basE;
textfield3.setText(""+result);
}
}
});
最佳答案
该错误是因为您尝试将字符串解析为 double 型。
这两个调用:
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
如果你看the documentation :
parseDouble 可以抛出两个异常:
NullPointerException
- 如果字符串为空NumberFormatException
- 如果字符串不包含可解析的 double 值。
您应该将这些调用放在 try catch block 中并捕获异常并提示用户错误,指出他们需要输入有效的数字。
这样的事情应该有效:
try{
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
result =number1+basE;
textfield3.setText(""+result);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Enter Valid Numbers In TextField", "Invalid TextFields", JOptionPane.ERROR_MESSAGE);
}
关于Java 修复文本字段上的字符串类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30327581/