简体   繁体   中英

Error message is displayed before going to next frame even though username and password is correct. (JAVA)

This is my txt file.

bk 456
bg 123
ll 222
pp 333

This is my code.

    String m_uname = ManagerID.getText();
    String m_pw = managerpw.getText();

    try
    {
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\L\\Desktop\\NewAssignmentOODJ\\textfile\\ManagerLoginDetails.txt"));
        String reader;
        boolean login = false;

        while ((reader = br.readLine())!=null)
        {
            String[] split = reader.split(" ");
            if (m_uname.equals(split[0]) && m_pw.equals(split[1]))
            {
                login = true;
                ManagerForm mform = new ManagerForm();
                mform.setVisible(true);
                this.setVisible(false);
                break;
            }

            else
            {
                JOptionPane.showMessageDialog(null,"Whoops!","Error",JOptionPane.ERROR_MESSAGE);
            }
        }
     }

    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
    }

Login function works but it displays error messages before it moves to next jframe form. Eg. if i input pp and 333, the error message will display 3 times before it moves to the next frame.

The first set of username and password works just fine.

You should only display a login error after the loop is finished executing. It's displaying the error three times because it's checking each pair before the next one, so when you put in "pp" and "333", it checks the first three pairs and sees that it's not a match, displaying three error messages before recognizing the last one as a match. Consider the following code:

String m_uname = ManagerID.getText();
String m_pw = managerpw.getText();

try
{
    BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\L\\Desktop\\NewAssignmentOODJ\\textfile\\ManagerLoginDetails.txt"));
    String reader;
    boolean login = false;

    while ((reader = br.readLine())!=null)
    {
        String[] split = reader.split(" ");
        if (m_uname.equals(split[0]) && m_pw.equals(split[1]))
        {
            login = true;
            ManagerForm mform = new ManagerForm();
            mform.setVisible(true);
            this.setVisible(false);
            break;
        }
    }
    if(!login)
    {
        JOptionPane.showMessageDialog(null,"Whoops!","Error",JOptionPane.ERROR_MESSAGE);
    }
 }

catch (Exception e)
{
    JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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