Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop from a specific point to another point in Java?

I'm working on a project in Java that is kind of like a digital time-machine, it basically saves what happened on a specific sate, archives it to a specific file, and stores it in a directory somewhere for safe keeping. Right now I'm working on a password function. I have the basics down for checking if it's right or wrong, but when I input the wrong answer, the class ends after saying "Invalid Password". Is there a way to have it loop from the end of else statement to the beginning of main so I don't have to re-execute the class everytime?

import java.util.Scanner;
import java.util.*;

public class Adam {

    public static void main(String args[]) {

        String passwrd = "password";
        String inputPassword;

        System.out.print("Please Input Password ");
        Scanner sc = new Scanner(System.in);
        inputPassword = sc.nextLine();

        if (inputPassword.equals(passwrd)) {
            System.out.println("Password Accepted, Loading Archive...");
        } else {
            System.out.println("Invalid Password");
        }
    }
}
like image 964
Gman0064 Avatar asked Dec 23 '15 10:12

Gman0064


2 Answers

You can use a do while loop, if user input is invalid then continue the loop else not.

import java.util.Scanner;
import java.util.*;

public class Adam {

    public static void main(String args[]) {
        String passwrd = "password";

        String inputPassword;
        boolean b = true;
        Scanner sc = new Scanner(System.in);
        do {

            System.out.print("Please Input Password ");

            inputPassword = sc.nextLine();

            if (inputPassword.equals(passwrd)) {

                System.out.println("Password Accepted, Loading Archive...");
                b = false;
            } else {

                System.out.println("Invalid Password");
                b = true;

            }

        } while (b);

    }
}

DEMO

like image 76
singhakash Avatar answered Nov 17 '22 05:11

singhakash


Whenever you want to run some code, check the result and then repeat if necessary the most obvious structure is do while.

Something like the following:

String inputPassword = null;
do {
    if (inputPassword != null)
        System.out.println("Invalid password");
     System.out.println("Enter password");
     inputPassword = sc.nextLine();
} while (!inputPassword.equals(password));
like image 2
sprinter Avatar answered Nov 17 '22 07:11

sprinter