1.11M Members

looping problem

 
0
 

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.

 
2
 

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)

 
0
 

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

 
1
 

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;

 
0
 

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

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article