0

Here is a simple version without any loops. How can I make it loop like "Wrong password. Try again." until user puts the right password instead stopping the program (or give them 3 chances before it stops)?

    import java.util.Scanner;
public class helloworld2
{
    public static void main(String[] arg)
    {
        Scanner q = new Scanner(System.in);
        long Pass;
        boolean auth = true;

        System.out.println("Enter Password :");
        Pass = q.nextLong();

        if ( Pass != 1234 )
           {
           System.out.println("Wrong Password!");
           auth = false;
           }
        else
           {
           System.out.println("Password Confirmed.");
           auth = true;
           }

        if (auth) {
            ////blablabla
            }

        else
          {
            return;
          }                 
    }
}
4
  • 2
    You need do-while loop. Commented Feb 4, 2013 at 17:48
  • 1
    variable names musn't be capitalized (Pass) That's for class names. Commented Feb 4, 2013 at 17:54
  • 1
    Just a simple note: Read the Java Sun convention =) Commented Feb 4, 2013 at 17:54
  • Bad idea to do things in the main method, its static definition makes it impossible to access non-static fields, instead instantiate a new helloworld2 object and define your behavior in the constructor. Commented Feb 4, 2013 at 18:28

1 Answer 1

3
public class helloworld2
{
    public static void main(String[] arg)
    {
        Scanner q = new Scanner(System.in);
        long Pass;
        boolean auth = true;
        boolean rightPassword = false;
        while(!rightPassword){//repeat until passwort is correct
          System.out.println("Enter Password :");
          Pass = q.nextLong();

          if ( Pass != 1234 )
          {
            System.out.println("Wrong Password!");
            auth = false;
          }
          else
          {
            rightPassword = true;//let the loop finish
            System.out.println("Password Confirmed.");
            auth = true;
          }
        }
        // Here do what you want to do
        //because here the user has entered a right password                 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.