首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JForm中的If Else和Exception

JForm中的If Else和Exception
EN

Stack Overflow用户
提问于 2022-06-10 13:24:56
回答 1查看 37关注 0票数 0

当用户在jtextfield中输入1和2以外的其他整数时,我试图抛出异常。

代码语言:javascript
复制
public class SearchEmployee extends javax.swing.JFrame  {

    /**
     * Creates new form SearchEmployee
     */
    public SearchEmployee() {
        
        initComponents();

    }
     // A utility function to check
    // whether a code is valid or not
       public static boolean isCodeValid(String id)
        throws IdNotFoundException
    {
        if(!id.equals("1")){
            throw new IdNotFoundException();
        }else if(!id.equals("2")){
            throw new IdNotFoundException();
        }
        else{
            return true;
        }
    }

据推测,在用户点击搜索按钮后,他们将进入新页面,在该页面中将显示员工的详细信息。

代码语言:javascript
复制
 private void searchActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        String id = staffID.getText();

        try{
            if(isCodeValid("1")){
                EmployeeDetails emp = new EmployeeDetails();
                emp.name.setText("Sky Peach");
                emp.email.setText("skypeach@gmail.com");
                emp.address.setText("Pangsapuri Sri Puteri");
                emp.phoneNo.setText("1999999999");
                emp.department.setText("IT");
                emp.designation.setText("Software Developer");
                emp.show();
            }else if(isCodeValid("2")){
                EmployeeDetails emp = new EmployeeDetails();
                emp.name.setText("Sky Orange");
                emp.email.setText("skyorange@gmail.com");
                emp.address.setText("Pangsapuri Sri Puteri");
                emp.phoneNo.setText("2999999999");
                emp.department.setText("IT");
                emp.designation.setText("Software Engineer");
                emp.show();
            }
        }catch (IdNotFoundException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        
        
        
  
    }   

但是,即使当我输入整数1和2时,也会引发异常。如何修复此错误?

EN

回答 1

Stack Overflow用户

发布于 2022-06-10 14:49:22

在注释中对Rogue和DevilsHnd答案进行扩展后,我建议切换用于字符串比较的参数。这避免了id参数为null时的NPEs。

代码语言:javascript
复制
public static boolean isCodeValid(String id) { return "1".equals(id) || "2".equals(id); }

或者在此之前进行异常空检查(防御性编程)。使用regex的方法更容易扩展。

代码语言:javascript
复制
public static boolean isCodeValid(String id) { 
    Objects.requireNonNull(id);
    return id.matches("[12]"); 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72575071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档