如下所示,我不断收到空字符串错误
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
我不确定为什么我一直收到此错误,因为我不会尝试在不在 JTextField 中键入数字的情况下进行计算。下面是我用于计算按钮的代码,非常简单。
private void ButtonCalculateActionPerformed(java.awt.event.ActionEvent evt) {
Height = Integer.parseInt(this.TextFieldHeight.getText());
Weight = Integer.parseInt(this.TextFieldWeight.getText());
BMI = Integer.parseInt(this.TextFieldBMI.getText());
answer = Height + Weight;
this.TextFieldBMI.setText("The answer is: " + answer);
}
这些是定义的变量
//variables
static int Height;
static int Weight;
static int BMI;
static int answer;
最佳答案
当 TextField 为空(getText() 返回“”)时会发生这种情况,因此 Integer 类无法解析任何内容并抛出异常。你应该用 try/catch
包围解析代码:
try{
Height = Integer.parseInt(this.TextFieldHeight.getText());
Weight = Integer.parseInt(this.TextFieldWeight.getText());
BMI = Integer.parseInt(this.TextFieldBMI.getText());
answer = Height + Weight;
this.TextFieldBMI.setText("The answer is: " + answer);
catch(NumberFormatEeceptinon e){
//So something when paring failed, e.g. show a error message
}
关于Java JTextField空字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568205/