【问题标题】:how to make an if else statement that checks if a textbox contains a specific string如何制作 if else 语句来检查文本框是否包含特定字符串
【发布时间】:2021-07-06 13:16:19
【问题描述】:

尝试在 Java 和 AWT 中制作登录表单。说明说唯一有效的用户名和密码分别是“name”和“12345”。如何创建一个 if else 语句来检查文本框是否包含那些特定的字符串?

    public static void main(String[] args) {
        
            Frame fm= new Frame ("My Login Form");
            fm.setSize (600,400);
            fm.setLayout (null);
            fm.setVisible (true);
            
            Label lblUsername= new Label("Username");
                lblUsername.setBounds(40,40,100,50);
                fm.add(lblUsername);
            
            TextField txtName,txtPass;
             
             txtName = new TextField();
                txtName.setBounds (150,50,200,25);
                fm.add(txtName);
             
            Label lblPassword= new Label ("Password");
                lblPassword.setBounds (40,80,100,50);
                fm.add(lblPassword);
            
              txtPass = new TextField();
                txtPass.setBounds (150,100,200,25);
                fm.add(txtPass);   
            
            Button btnLogin,btnClear,btnExit;
            
            btnLogin= new Button("Login");
                btnLogin.setBounds (40,120,60,35);
                fm.add(btnLogin);
                btnLogin.addActionListener((ActionEvent e) -> {
                    
                if ( txtName.contains("name") && lblPassword.contains("12345"))
                { 
                }
                else
                {
               
                }
            }); 
   }
}

【问题讨论】:

    标签: java awt


    【解决方案1】:

    由于 txtNamelblPassword 不是字符串,而是分别是 TextFieldLabel 对象,所以你必须使用 Java 的getText()equals() 方法检查文本值是否相同。使用 == 而不是 equals() 将比较字符串的内存地址而不是它们包含的文本,因此它们总是不同的。这个 if 语句应该可以正常工作:

    if (txtName.getText().equals("name") && lblPassword.getText().equals("12345"))
    

    【讨论】:

      【解决方案2】:

      您已接近解决方案。 不要使用包含,而是使用 == 。

      对于“name123”和“name”,Contains 也会返回 true。您只需严格检查“名称”即可。

      检查以下代码:

      if ( txtName == "name" && lblPassword == "12345")
      { 
      // match successfull
      }
      else
      {
       // throw error           
      }
      

      如果你愿意,你也可以嵌套 if 条件:

       if ( txtName == "name")
        if (lblPassword == "12345")
          { 
          // match successfull
          }
          else
          {
           // throw error           
          }
      

      【讨论】:

      • 我收到一条错误消息,提示 Textfield 和 String 现在是不兼容的类型
      • 使用 getText() 函数从 textField 中获取值。像这样 -> txtName.getText() == "name"
      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 2018-03-16
      • 2013-02-24
      • 2014-01-08
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2016-03-26
      相关资源
      最近更新 更多