即使 try 块满足上述条件,Java 代码中的 Catch 块也会被执行?

问题描述

我是 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");
            }
        }           
    });

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)