Hello everyone! I'm currently having a problem with my program it doesn't loop properly please help me with it. The code is below. Thanks in advance!

import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.*;
    public class Wewe{
        public static void main(String[]args){
            Scanner inp = new Scanner(System.in);
            boolean tryAgain;


            do{
            System.out.print("\nInput username: ");
            String user = inp.nextLine();
            System.out.print("\nInput password: ");
            String pass = inp.nextLine();

        if(user.equals("admin") && pass.equals("admin")){
                System.out.print("Success!");
                tryAgain = true;
            }
            if(user!="admin" && pass!="admin"){
                JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
            tryAgain = false;
        }
    }while(tryAgain = true);
            }
        }

What I want to happen is that once the user entered wrong username or password the program will then loop. But if the user entered the correct username or password, it wont loop asking the user for the correct one.

Recommended Answers

All 4 Replies

while(tryAgain = true)

= is assignment, to test for equals use ==

but in this case, since tryAgain is already a boolean (true or false) yu can just say
while (tryAgain)

Hi sir I tried your suggestion but it gave me an error. It says vairable tryAgain might not have been initialized.

That's because the compiler has seen that the two if tests on lines 16 and 20 could both be false, in which case neither of the assignments on lines 18 and 22 will be executed, and the tryAgain variable will not have been initialised by you.
You need to decide what the correct value of tryAgain should be if both if tests fail, and initialise tryAgain to that value when you declare it, eg by changing line17 to boolean tryAgain = true;

@angel-do as @James has explained.
Either initialize variable tryAgain or add else statement for two if with the values of "tryAgain" in them.

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.