繁体   English   中英

如何打破这个 java 程序中的 while 循环

[英]How to break the while loop in this java program

我正在使用 java 进行登录。 身份验证继续循环并显示错误消息,直到它获得正确的用户名和密码。 如何解决? 我只希望它在找到时破坏,并且仅在未找到时显示未找到。

private void loginbtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String username = usertxt.getText();
    String password = passwordtxt.getText();
    
    try
    {
        File login = new File("logindata.txt");
        Scanner scan = new Scanner(login);
        scan.useDelimiter("[,\n]");
        
        while(scan.hasNext())
        {
            String user = scan.next();
            String pass = scan.next();
            
            if (username.equals(user.trim()) && password.equals(pass.trim()))
            {
               JOptionPane.showMessageDialog(null,"Welcome!"+username);
               this.dispose();
               new peopleoptions().setVisible(true);
               break;
            }
            else
            {
                JOptionPane.showMessageDialog(null,"User not found, please register");                    
            }
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,"System Error");
    }
}

我的评论作为代码,几乎没有重新思考:

...
  scan.useDelimiter("[,\n]");
  boolean found = false; // Memorize...    
  while (!found && scan.hasNext()) { // ...process until found or end ("until(x or y)" <=> "while not(x and y)";)
    String user = scan.next();
    String pass = scan.next();            
    if (username.equals(user.trim()) && password.equals(pass.trim())) {
      found = true; // .. don't break...
    } 
  }
  // show dialog (and do "the action") only after "processing database" ...
  if (found) {
    // log.info("yay");
    JOptionPane.showMessageDialog(null,"Welcome!"+username);
    new peopleoptions().setVisible(true);
  } else { // ... AND not found!;)
    JOptionPane.showMessageDialog(null,"Credentials invalid, please register new user or reset password");                    
  }
  // really??: this.dispose(); // in any case?? maybe: "finally"!
}  catch( ...

面对眼前的问题,它归结为:

  • 通过文件循环,设置 boolean 标志
  • 然后正确的事情。

请“释放”您的资源(文件、扫描仪……)!!

如何正确关闭资源

java >= 8:

试用资源

分别测试用户和密码:

while (scan.hasNext()) {
    String user = scan.next();
    String pass = scan.next();
        
    if (username.equals(user.trim())) {
        if (password.equals(pass.trim())) {
            JOptionPane.showMessageDialog(null, "Welcome!"+username);
            dispose();
            new peopleoptions().setVisible(true);
            break;
        } else {
            JOptionPane.showMessageDialog(null, "Password incorrect. Please try again");
        }
    } else {
        JOptionPane.showMessageDialog(null, "User not found, please register");
    }                
 }

不要在 if 中使用 break 命令,而应该在 While 中使用它。 或者你可以试试 if condition scan.hasNext() = false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM