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

我在让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循环编码错误,因为“login failed”joptionpane else块不应在while循环内。相反,在循环之前声明一个布尔值,将其设置为false,检查是否在该循环中找到用户名/密码,如果是,则将布尔值设置为true。然后在循环之后检查布尔值,如果为false,则显示错误消息。

若要了解原因,请使用调试器运行代码以了解其行为方式的原因。更重要的是,学习“橡皮鸭”调试技术,在这里你可以在精神上或纸上浏览代码,告诉鸭子每一行代码应该做什么。

为了说明这一点,您的代码的行为类似于下面的代码,其中一个布尔数组模拟您的密码用户名检查。当然,您将使用一个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次尝试时匹配(第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");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值