Home > Mobile >  How to break the while loop in this java program
How to break the while loop in this java program

Time:11-28

Im making a login using java. The authentication keeps on looping and displaying error message until it gets the username and password right. How to fix it? I only want it to break if found and only show not found when not found.

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");
    }
}

CodePudding user response:

My comment as code, with little re-thinking:

...
  scan.useDelimiter("[,\n]");
  boolean found = false; // Memorize...    
  while (!found && scan.hasNext()) { // ...process until found or end ("until(x or y)" <=> "while (not x and not y)" <==> "while not(x or 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( ...

With the problem at hand, it comes down to:

  • looping trough the file, setting a boolean flag
  • then afterwards doing the correct stuff.

And please "free" your resources (File, Scanner, ...)!!

How to Correctly Close Resources

With java >= 8:

Try-With-Resources

CodePudding user response:

Instead of using the break command in if, you should use it in While. Or can you try in if condition scan.hasNext() = false

  • Related