如何制作一个 if else 语句来检查文本框是否包含特定字符串
how to make an if else statement that checks if a textbox contains a specific string
正在尝试在 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
{
}
});
}
}
您即将找到解决方案。
不要使用包含,而是使用 == .
“name123”和“name”也将 return 包含在内。您只需要严格检查“姓名”即可。
检查下面的代码:
if ( txtName == "name" && lblPassword == "12345")
{
// match successfull
}
else
{
// throw error
}
如果需要,您还可以嵌套 if 条件:
if ( txtName == "name")
if (lblPassword == "12345")
{
// match successfull
}
else
{
// throw error
}
因为 txtName 和 lblPassword 不是字符串而是 TextField 和 Label 对象,你必须使用 Java 的方法 getText() 和 equals() 来检查文本值是相同的。使用 == 而不是 equals() 将比较字符串的内存地址而不是它们包含的文本,因此它们总是不同的。 if 语句应该可以正常工作:
if (txtName.getText().equals("name") && lblPassword.getText().equals("12345"))
正在尝试在 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
{
}
});
}
}
您即将找到解决方案。 不要使用包含,而是使用 == .
“name123”和“name”也将 return 包含在内。您只需要严格检查“姓名”即可。
检查下面的代码:
if ( txtName == "name" && lblPassword == "12345")
{
// match successfull
}
else
{
// throw error
}
如果需要,您还可以嵌套 if 条件:
if ( txtName == "name")
if (lblPassword == "12345")
{
// match successfull
}
else
{
// throw error
}
因为 txtName 和 lblPassword 不是字符串而是 TextField 和 Label 对象,你必须使用 Java 的方法 getText() 和 equals() 来检查文本值是相同的。使用 == 而不是 equals() 将比较字符串的内存地址而不是它们包含的文本,因此它们总是不同的。 if 语句应该可以正常工作:
if (txtName.getText().equals("name") && lblPassword.getText().equals("12345"))