Hi, I'm doing a study planner in java. I'm doing a simple login system. For every user who registers a text file is created holding all of the information inputted during registration. This is the code of a method which the program uses to login the user:

public void loginUser(){

    r = new Registration();

    r.username = txtUser.getText();
    r.password = txtPass.getText();

    try{


        String line;

        SubjectFrame subject = new SubjectFrame();

        BufferedReader f = new BufferedReader(new FileReader(r.username + ".txt"));


        while((item = f.readLine()) != null){

            if(line.equals(r.password)){

                dispose();
                subject = new SubjectFrame();
                subject.setSize(700,600);
                subject.setLocation(100,100);
                subject.setVisible(true);
            }else{
                System.out.println("No");
            }

        }
        f.close();
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

The problem is that when the user inputs wrong details I get 4 'No'('No' is used for debugging instead of an error message). When the user inputs the correct details I get 4 'No' but it proceeds properly. I know it's something concerning the loop but I can't figure it out. I'm still a beginner :(

Anyway thanks in advance!

Recommended Answers

All 3 Replies

Because the if/else/print"no" is inside the while loop it will be executed once for each line in the file. Your logic should check for the password being in the file, then display the frame or the error afterwards. Something like this (pseudo-code)

boolean passwordFound = false
read each line of the file...
   if password matches set passwordFound = true
after end of file...
   if (passwordFound) show frame
   else show error message

Also the message: No is not too useful. Better for debugging would be to print out the values of line and r.password so you cann see what the computer is seeing so you'd know why the if test failed.

Thanks James !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.