gpt4 book ai didi

java - 即使 else if 条件通过,else 语句仍然运行

转载 作者:搜寻专家 更新时间:2023-10-30 20:23:42 24 4
gpt4 key购买 nike

我在让 if else 语句正常工作时遇到问题,这里我有一个使用数据库值的表单登录。 Employee 角色的语句工作正常,但即使 else if 语句通过,else 语句仍然运行。

如果有帮助,如果 Customer 语句通过,对话框出现两次,如果 else 自行运行,对话框出现三次。如果我的代码格式不正确,我深表歉意,我是新来的,在这里发布代码。

 private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                          
// action performed when the login button is pressed
// variables that will contain the row entries to the login data base (user name)
String userNameDb = "";
roleDb = rs.getString("role");
//database connection code
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("//database directory");
st=con.createStatement();
//selects entries from the userName password and role row from the user table
rs=st.executeQuery("Select userName, role From tblUser ;");

//loops through the table entires
while(rs.next())
{
//assigns database entry to variables
userNameDb = rs.getString("userName");
roleDb = rs.getString("role");

if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
//if the users input and role match the data base for an customer send them to the selection form
else if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
else
{
JOptionPane.showMessageDialog(null, "Login failed");

}
}
}
catch(Exception ex)
{
System.out.println("" + ex);
}
}
}

最佳答案

问题是您的 while 循环编码错误,因为您的“登录失败”JOptionPane else block 不应该在 while 循环内。相反,在循环之前声明一个 boolean 值,将其设置为 false,检查是否在该循环中找到了用户名/密码,如果是,则将 boolean 值设置为 true。然后循环之后检查 boolean 值,如果为假,则显示错误消息。

要了解原因,请使用调试器运行代码以查看其行为方式的原因。更重要的是,学习“橡皮鸭”调试技术,您可以在心里或在纸上检查代码,告诉鸭子每行代码应该做什么。

为了说明,您的代码的行为类似于下面的代码,其中 boolean 数组模仿您的密码用户名检查。当然,您会使用 while 循环,而不是 for 循环,但这里使用它是为了使示例更简单:

private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
for (boolean loopItem : loopItems) {
if (loopItem) {
break;
} else {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}

假设密码/用户名仅在第 4 次尝试时匹配(第四项为 true),那么对于每次失败的检查,JOptionPane 将显示登录失败。你想要的是这样的:

private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
boolean userFound = false;

// you'll of course be using a while loop here
for (boolean loopItem : loopItems) {
if (loopItem) {
userFound = true;
// do something with user data
break;
}
}
if (!userFound) {
JOptionPane.showMessageDialog(null, "Login failed");
}
}

关于java - 即使 else if 条件通过,else 语句仍然运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50651359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com