【发布时间】:2021-07-14 11:50:04
【问题描述】:
我是 Java 新手,我尝试在我的 Java 代码中使用异常来提醒用户,如果他/她在文本字段中键入负数或非数字值。但是,当我输入一个个位数的正数时,catch 块会被执行。
//textfield to enter the amount of Rs.
txt_rupees = new JTextField();
//KeyListener to check if the content entered in the text field is a number or not.
txt_rupees.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
try {
//convert the user input in the textfield from string to double
double check = Double.parseDouble(txt_rupees.getText());
//checking if the number entered by the user is positive or not.
if (check > 0) {
lb_check1.setText(" ");
}
else {
lb_check1.setText("Please enter a valid number");
}
}
catch (NumberFormatException ne){
//If the user enters a non-numerical character then this message should be displayed by the label.
lb_check1.setText("ALERT: Please enter a valid float or int value in the textfield");
}
}
});
【问题讨论】:
-
只有当
NumberFormatException被扔进 de try 块时才会执行你的 catch 块。很可能你插入了数字,但是解析函数会为任何事情抛出错误(也许它在 keyPressed 事件上只是空的)。跟踪ne错误以便更准确地确定错误
标签: java exception try-catch catch-block